LeetCode-Binary Tree Paths

LiBlog發表於2016-09-14

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

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

 Solution:
/**
 * 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> resList = new LinkedList<String>();
        StringBuilder builder = new StringBuilder();
        binaryTreePaths(root,builder,resList);
        return resList;
    }
    
    public void binaryTreePaths(TreeNode cur, StringBuilder builder, List<String> resList){
        if (cur==null){
            return;
        }
        
        builder.append(cur.val);
        if (cur.left==null && cur.right==null){
            resList.add(builder.toString());
            return;
        }
        
        builder.append("->");
        int len = builder.length();
        binaryTreePaths(cur.left,builder,resList);
        builder.setLength(len);
        binaryTreePaths(cur.right,builder,resList);
    }
}

 

相關文章