Thursday, February 11, 2016

[LintCode] 480 Binary Tree Paths 解题报告

Description
Given a binary tree, return all root-to-leaf paths.


Example
Given the following binary tree:

   1
 /   \
2     3
 \
  5
All root-to-leaf paths are:

[
  "1->2->5",
  "1->3"
]



思路
DFS。一层一层往下走并且更新path,如果发现已经到leaf了,那么把整个path加到result里去。


Code
/**
 * 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<String> binaryTreePaths(TreeNode root) {
        // Write your code here
        List<String> result = new ArrayList<>();
        if (root == null) {
            return result;
        }
        
        helper(result, "" + root.val, root);
        return result;
    }
    
    public void helper(List<String> result, String path, TreeNode root) {
        if (root.left == null && root.right == null) {
            result.add(path);
            return;
        }
        
        if (root.left != null) {
            helper(result, path + "->" + root.left.val, root.left);
        }
        
        if (root.right != null) {
            helper(result, path + "->" + root.right.val, root.right);
        }
        
    }
}