码迷,mamicode.com
首页 > 其他好文 > 详细

lintcode-easy-Binary Tree Paths

时间:2016-02-21 12:57:42      阅读:304      评论:0      收藏:0      [点我收藏+]

标签:

Given a binary tree, return all root-to-leaf paths.

 

 

这道题主要利用一下java的一个特性,String是immutable的对象,不能修改,只能重新生成

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */
public class Solution {
    /**
     * @param root the root of the binary tree
     * @return all root-to-leaf paths
     */
    public List<String> binaryTreePaths(TreeNode root) {
        // Write your code here
        List<String> result = new ArrayList<String>();
        if(root == null)
            return result;
        
        String str = null;
        helper(str, result, root);
        
        return result;
    }
    
    public void helper(String str, List<String> result, TreeNode root){
        if(root.left == null && root.right == null){
            if(str == null){
                str = String.valueOf(root.val);
            }
            else{
                str = str + "->" + String.valueOf(root.val);
            }
            result.add(str);
            return;
        }
        
        String new_str = null;
        
        if(str == null){
            new_str = String.valueOf(root.val);
        }
        else{
            new_str = str + "->" + String.valueOf(root.val);
        }
        
        if(root.left != null)
            helper(new_str, result, root.left);
        
        if(root.right != null)
            helper(new_str, result, root.right);
        
        return;
        
    }
}

 

lintcode-easy-Binary Tree Paths

标签:

原文地址:http://www.cnblogs.com/goblinengineer/p/5204649.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!