首页 > 其他 > 详细

257. Binary Tree Paths 257.二叉树路径

时间:2020-05-25 11:22:55      阅读:57      评论:0      收藏:0      [点我收藏+]

Given a binary tree, return all root-to-leaf paths.

Note: A leaf is a node with no children.

Example:

Input:

   1
 /   2     3
   5

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

Explanation: All root-to-leaf paths are: 1->2->5, 1->3

这种路径题的也不一定要用root.right = ,路径内容:DFS(起点,过程,结果)


recursive的三种模板:

root.left = trimBST(root.left, L, R);自己等于自己的调用

convertBST(root.right); 就光是自己
node.left = helper(nums, left, mid - 1); index

 

helper() 就还是左右都加?这中间怎么权衡的啊。左边的计算就只包括左边一线,这是traverse的自带优势。以前不懂。

 

叶子节点的特征是左右都没东西了,这个需要利用。从而找到一个字符串的开头。

 

技术分享图片
class Solution {
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> ans = new ArrayList<String>();
        //cc
        if (root == null) return ans;
        findBT(root, "", ans);
        return ans;
    }
    
    public void findBT(TreeNode root, String path, List<String> ans) {
        //边界情况,叶子节点
        if ((root.left == null) && (root.right == null))
            ans.add(path + root.val);
        
        //左右递归
        if (root.left != null)
            findBT(root.left, path + root.val + "->", ans);
        if (root.right != null)
            findBT(root.right, path + root.val + "->", ans);
    }
}
View Code

 

 

257. Binary Tree Paths 257.二叉树路径

原文:https://www.cnblogs.com/immiao0319/p/12955559.html

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