257. Binary Tree Paths返回所有深度优先的遍历

[抄题]:

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

For example, given the following binary tree:

 

   1
 /   \
2     3
 \
  5

 

All root-to-leaf paths are:

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

 [暴力解法]:

时间分析:

空间分析:

[奇葩corner case]:

[奇葩输出]:

看到["1->2->5", "1->3"]就吓懵了,其实就是字符串数组啊

[思维问题]:

以为这下需要汇总再返回了,其实不用,返回也是参数化了,在函数参数中进行的

[一句话思路]:

  1. 左子树非空就递归左边,右子树非空就递归右边。划分的条件是左右,以前用过但是不懂。

[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

[画图]:

[一刷]:

  1. 叶子结点象征一条路的结束,可以把路添加到ans中。

[二刷]:

[三刷]:

[四刷]:

[五刷]:

  [五分钟肉眼debug的结果]:

[总结]:

  1. 叶子结点象征一条路的结束,可以把路添加到ans中。

[复杂度]:Time complexity: O(n) Space complexity: O(n)

[英文数据结构或算法,为什么不用别的数据结构或算法]:

二叉树的原理是先走到最底层叶子结点,然后返回根节点开始调用

[关键模板化代码]:

 void findBT(TreeNode root, String path, List<String> ans) {
        if (root.left == null && root.right == null) 
            ans.add(path + root.val);//add here since it's an sign of end
        if (root.left != null) findBT(root.left, path + root.val + "->", ans);
        if (root.right != null) findBT(root.right, path + root.val + "->", ans);
    }
path ans都作为helper的参数

[其他解法]:

[Follow Up]:

[LC给出的题目变变变]:

 [代码风格] :

/**
 * 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 List<String> binaryTreePaths(TreeNode root) {
        //corner case
        List<String> ans = new ArrayList<>();
        if (root == null) {
            return ans;
        }
        findBT(root, "", ans);
        return ans;
    }
    
    void findBT(TreeNode root, String path, List<String> ans) {
        if (root.left == null && root.right == null) 
            ans.add(path + root.val);//add here since it's an sign of end
        if (root.left != null) findBT(root.left, path + root.val + "->", ans);
        if (root.right != null) findBT(root.right, path + root.val + "->", ans);
    }
}
View Code

 

posted @ 2018-03-11 11:20  苗妙苗  阅读(169)  评论(0编辑  收藏  举报