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

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

时间:2016-01-13 13:04:43      阅读:148      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!