• 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);
     
  • 相关阅读:
    64位整数乘法
    HTML中常见问题汇总贴
    题解 牛客【「水」悠悠碧波】
    题解 CF1391B 【Fix You】
    四级-句子
    快速幂||取余运算
    最大子列和
    JvavScript中的函数与对象
    JavaScript中的流程控制语句
    冒泡排序,选择排序,插入排序,归并排序
  • 原文地址:https://www.cnblogs.com/bbbblog/p/5349967.html
Copyright © 2020-2023  润新知