Monday, September 7, 2015

Binary Tree Paths

Given a binary tree, return all root-to-leaf paths.
For example, given the following binary tree:
   1
 /   \
2     3
 \
  5
All root-to-leaf paths are:


["1->2->5", "1->3"]
Solution: DFS

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List binaryTreePaths(TreeNode root) {
        ArrayList result = new ArrayList();

        if (root == null) {
            return result;
        }
        
        dfs(root, result, new StringBuilder());

        return result;
    }
    
    public void dfs(TreeNode root, ArrayList result, StringBuilder path) {
        if (root.left == null && root.right == null) {
            path.append(root.val);
            result.add(path.toString());
            return;
        }
        
        path.append(root.val);
        path.append("->");
        
        if (root.left != null) {
            dfs(root.left, result, new StringBuilder(path));
        }
        
        if (root.right != null) {
            dfs(root.right, result, new StringBuilder(path));
        }
    }
}

No comments:

Post a Comment