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

lintcode:二叉树的所有路径

时间:2016-04-03 17:16:38      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:

二叉树的所有路径

给一棵二叉树,找出从根节点到叶子节点的所有路径。

样例

给出下面这棵二叉树:

   1
 /   2     3
   5

所有根到叶子的路径为:

[
  "1->2->5",
  "1->3"
]

解题
深度优先 可以转换成先序遍历:根左右,根结点遍历以后,遍历两个子树,是叶子结点的时候保存路径
/**
 * 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 ArrayList<String> binaryTreePaths(TreeNode root) {
        // Write your code here
        ArrayList<String> result = new ArrayList<String>();
        if(root == null)
            return result;
        String path="";
        Paths(root,result,path);
        return result;
    }
    public void Paths(TreeNode root,ArrayList<String> result,String path){
        if(root == null)
            return;
        if(root.left==null && root.right == null){
            if( path.equals(""))
                path += root.val;
            else 
                path +="->"+root.val;
            result.add(path);
            return;
        }
        if( path.equals(""))
            path += root.val;
        else 
            path +="->"+root.val;
        Paths(root.left,result,path);
        Paths(root.right,result,path);
        
    }
}

 

后面两行代码互换对结果没有影响,只是所有路径的先后次序发生了变化

Paths(root.right,result,path);
Paths(root.left,result,path);

 

 

lintcode:二叉树的所有路径

标签:

原文地址:http://www.cnblogs.com/theskulls/p/5349967.html

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