LeetCode 257. Binary Tree Paths

原题链接在这里:https://leetcode.com/problems/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"]

题解:

DFS 依次添加,终止条件是叶子节点。

Note:1. 若使用StringBuilder就要做copy.

e.g. [1,2,3], 会写成["1->2","1->23"]. 因为扫过点2,StringBuilder 会变成1->2, 扫过点3,原来的点2没有去掉,就会变成1->23,但是第一个结果没有变成1->23是因为,用到sb.toString()时自动做了copy by value.

2 . 但如果使用String,在递归调用时可以直接使用str, 因为String 和 int, float一样是priority type, 是copy by value,而不像array等object 是 copy by reference.

Time Complexity: O(n), 这是dfs. Space: O(h). h是树的高度,一共用了h层stack.

AC  Java:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> res = new ArrayList<String>();
        if(root == null){
            return res;
        }
        dfs(root, new StringBuilder(), res);
        return res;
    }
    private void dfs(TreeNode root, StringBuilder sb, List<String> res){
        
        if(root.left == null && root.right == null){
            sb.append(root.val);
            res.add(sb.toString());
            return;
        }
        sb.append(root.val);
        sb.append("->");
        if(root.left != null){
            dfs(root.left,new StringBuilder(sb),res);
        }
        if(root.right != null){
            dfs(root.right,new StringBuilder(sb),res);
        }
    }
}

上面使用StringBuilder, 下面使用String.

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     public List<String> binaryTreePaths(TreeNode root) {
12         List<String> res = new ArrayList<String>();
13         if(root == null){
14             return res;
15         }
16         dfs(root, "", res);
17         return res;
18     }
19     private void dfs(TreeNode root, String str, List<String> res){
20         if(root.left == null && root.right == null){
21             str = str + root.val;
22             res.add(str);
23         }
24         str = str + root.val + "->";
25         if(root.left != null){
26             dfs(root.left, str, res);
27         }
28         if(root.right != null){
29             dfs(root.right, str, res);
30         }
31     }
32 }

类似Path SumSmallest String Starting From LeafSum Root to Leaf Numbers.

转载于:https://www.cnblogs.com/Dylan-Java-NYC/p/4824983.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值