leetcode 257: Binary Tree Paths

1393 단어

Binary Tree Paths


Total Accepted: 3755
Total Submissions: 17536
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"]
[ ]
 . 
[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> res = new ArrayList<>();
        if(root==null) return res;
        StringBuilder sb = new StringBuilder();
        rec(root, res, sb);
        return res;
    }
    
    private void rec(TreeNode root, List<String> res, StringBuilder sb) {
        if(root.left==null && root.right==null) {
            sb.append(root.val);
            res.add(sb.toString());
            return;
        }
        
        sb.append(root.val);
        sb.append("->");
        int oriLen = sb.length();
        
        if(root.left!=null) rec(root.left, res, sb);
        sb.setLength(oriLen);
        if(root.right!=null) rec(root.right, res, sb);
        
    }
}

좋은 웹페이지 즐겨찾기