首页 > 其他 > 详细

Jan 12 - Binary Tree Paths; Tree; Recursion; DFS;

时间:2016-01-13 13:01:40      阅读:125      评论:0      收藏:0      [点我收藏+]

代码:

/**
 * 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> list = new ArrayList<>();
        if(root == null) return list;
        String s = "";
        addTreePath(root, root.val, s, list);
        return list;
    }
    
    public void addTreePath(TreeNode root, int val, String s, List<String> list){
        if(root.left == null && root.right == null){
            list.add(s+root.val);
        }
        else if(root.left != null && root.right == null){
            addTreePath(root.left, val, s+root.val+"->", list);
        }
        else if(root.left == null && root.right != null){
            addTreePath(root.right, val, s+root.val+"->", list);
        }
        else{
            addTreePath(root.left, val, s+root.val+"->", list);
            addTreePath(root.right, val, s+root.val+"->", list);
        }
    }
}

  

Jan 12 - Binary Tree Paths; Tree; Recursion; DFS;

原文:http://www.cnblogs.com/5683yue/p/5126828.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!