2015年11月4日星期三

Leetcode 257 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 1: DFS
 public class Solution {  
   public List<String> binaryTreePaths(TreeNode root) {  
     List<Integer> one=new ArrayList<>();  
     List<String> res=new ArrayList<>();  
     if (root!=null) dfs(root,one,res);  
     return res;  
   }  
   private void dfs(TreeNode x, List<Integer> one, List<String> res) {  
     one.add(x.val);  
     if (x.left!=null) dfs(x.left,one,res);  
     if (x.right!=null) dfs(x.right,one,res);  
     if (x.left==null && x.right==null) {  
       StringBuilder sb=new StringBuilder();  
       for (int num: one) {  
         sb.append(String.valueOf(num));  
         sb.append("->");  
       }  
       res.add(sb.substring(0,sb.length()-2));  
     }  
     one.remove(one.size()-1);  
   }  
 }  

没有评论:

发表评论