LintCode - 二叉树的所有路径(普通)

版权声明:本文为博主原创文章,未经博主允许不得转载。

难度:容易
要求:

给一棵二叉树,找出从根节点到叶子节点的所有路径。

样例给出下面这棵二叉树:

   1
 /   \
2     3
 \
  5

所有根到叶子的路径为:

[
  "1->2->5",
  "1->3"
]
/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */
public class Solution {
    /**
     * @param root the root of the binary tree
     * @return all root-to-leaf paths
     */
    public List binaryTreePaths(TreeNode root) {
        // Write your code here
        List list = new ArrayList();
        
        if(root != null){
            addPath(root,String.valueOf(root.val), list);
        }

        return list;
    }
    
    public void addPath(TreeNode node,String path,List list){
        if(node == null){
            return;
        }
        
        if(node.left == null && node.right == null){
            list.add(path);
        }
        
        if(node.left != null){
            addPath(node.left,path + "->" + String.valueOf(node.left.val),list);
        }
        
        if(node.right != null){
            addPath(node.right,path + "->" + String.valueOf(node.right.val),list);
        }
    }
}

你可能感兴趣的:(LintCode - 二叉树的所有路径(普通))