2015年8月15日星期六

[LeetCode] Binary Tree Paths

Problem:

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"]

Java Code:

/**
 * 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<String> binaryTreePaths(TreeNode root) {
        List<String> result = new ArrayList<String>();
        if (root == null) {
            return result;
        }
        
        List<Integer> path = new ArrayList<Integer>();
        helper(root, path, result);
        return result;
    }
    
    private void helper(TreeNode root, List<Integer> path, List<String> result) {
        path.add(root.val);
        if (root.left != null) {
            helper(root.left, path, result);
        }
        if (root.right != null) {
            helper(root.right, path, result);
        } 
        if (root.left == null && root.right == null) {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < path.size(); i++) {
                sb.append(path.get(i));
                if (i != path.size() - 1) {
                    sb.append("->");
                }
            }
            result.add(new String(sb));
        }
        path.remove(path.size() - 1);
    }
}

这个递归解法感觉有些复杂了,有没有更简单的解法呢?

没有评论:

发表评论