zoukankan      html  css  js  c++  java
  • lintcode:二叉树的所有路径

    二叉树的所有路径

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

    样例

    给出下面这棵二叉树:

       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);
     
  • 相关阅读:
    IT面试技巧(2)
    mySQL学习入门教程——4.内置函数
    weight decay (权值衰减)
    c++读取文件目录
    caffe 卷积层的运算
    一个物体多个标签的问题
    python caffe 在师兄的代码上修改成自己风格的代码
    caffe 细节
    vim让一些不可见的字符显示出来吧
    python 读写文件
  • 原文地址:https://www.cnblogs.com/bbbblog/p/5349967.html
Copyright © 2011-2022 走看看