LeetCode 257. Binary Tree Paths

题目:

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

打印binary tree的所有根到叶子的路径,感觉和之前做的path sum 2差不多,也是用到了一点回溯的思想。helper function里先把当前节点加入temp,然后check如果root是叶子的话就把当前路径加到result里,如果不是叶子的话就要左右两边分别继续递归,递归完了要记得remove掉。

Runtime: 1 ms, faster than 99.98% of Java online submissions for Binary Tree Paths.

Memory Usage: 39.5 MB, less than 7.90% of Java online submissions for Binary Tree Paths.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> result = new ArrayList<>();
        if (root == null) {
            return result;
        }
        helper(root, new ArrayList<>(), result);
        return result;
    }
    
    public void helper(TreeNode root, List<Integer> temp, List<String> result) {
        temp.add(root.val);
        if (root.left == null && root.right == null) {
            StringBuilder sb = new StringBuilder();
            for (int i : temp) {
                sb.append(i);
                sb.append("->");
            }
            result.add(sb.substring(0, sb.length() - 2).toString());
            return;
        }
        if (root.left != null) {
            helper(root.left, temp, result);
            temp.remove(temp.size() - 1);
        }
        if (root.right != null) {
            helper(root.right, temp, result);
            temp.remove(temp.size() - 1);
        }
    }
}

看了下257. Binary Tree Paths · leetcode发现人家并不用回溯remove?我也不是很懂了,暂时不想研究了。

2023.1.13

上次这题做到一半跑了,今天接着上次wrong answer的代码就自己给改出来了。这里我采用的方法是用一个list来记录所有treenode,每次遇到一个就加进去一个,最后在这个方向递归完了以后需要把它们remove掉,不然就会带到后面的递归中。看了下大家的解法,很多都直接采用string作为参数,我猜因为string是immutable的,而list在被传入参数的时候还在被修改,所以递归回去以后新的节点都还在list里,因此需要删掉(真的是猜的,现在不想动脑了,以后再考证)。

具体的递归有两种写法,一种是判断root == null的情况,这样后面就不用单独判断左右子节点是否存在;另一种就是反过来。代码都贴了上来。

哦对,这个递归的本质其实也就是preorder traversal了。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> result = new ArrayList<>();
        helper(root, new ArrayList<>(), result);
        return result;
    }

    private void helper(TreeNode root, List<TreeNode> temp, List<String> result) {
        // option 1 part 1
        if (root == null) {
            return;
        }
        System.out.println(root.val);
        if (root.left == null && root.right == null) {
            temp.add(root);
            result.add(buildString(temp));
            temp.remove(root);
        }
        // option 1 part 2
        temp.add(root);
        helper(root.left, temp, result);
        helper(root.right, temp,result);
        temp.remove(root);
        // option 2
        // if (root.left != null) {
        //     temp.add(root);
        //     helper(root.left, temp, result);
        //     temp.remove(root);
        // }
        // if (root.right != null) {
        //     temp.add(root);
        //     helper(root.right, temp, result);
        //     temp.remove(root);
        // }
    }

    private String buildString(List<TreeNode> list) {
        StringBuilder sb = new StringBuilder();
        for (TreeNode node : list) {
            sb.append(node.val);
            sb.append("->");
        }
        return sb.substring(0, sb.length() - 2).toString();
    }
    
}

用string做的代码就很简单了。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> result = new ArrayList<>();
        helper(root, "", result);
        return result;
    }

    private void helper(TreeNode root, String str, List<String> result) {
        if (root == null) {
            return;
        }
        if (root.left == null && root.right == null) {
            result.add(str + root.val);
        }
        helper(root.left, str + root.val + "->", result);
        helper(root.right, str + root.val + "->", result);
    }    
}

然后是BFS/DFS迭代,跟112一样,也是两个几乎是一样的,除了用的数据结构不同。自己写还是没写出来,本来还是想存成一个list然后转成string,但是怎么写都不对,最后还是向string(答案)屈服了。其实仔细想想也对,每个节点对应的path都应该也用一个queue/stack存起来,不然就要回溯remove它(但因为对每个节点都存所以感觉就巨麻烦),所以如果要用list的话得是a queue/stack of list,which太复杂了,不如直接用string了。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> result = new ArrayList<>();
        Queue<String> paths = new LinkedList<>();
        Queue<TreeNode> queue = new LinkedList<>();
        if (root == null) {
            return result;
        }
        queue.add(root);
        paths.add("");
        while (!queue.isEmpty()) {
            TreeNode node = queue.remove();
            String str = paths.remove();
            if (node.left == null && node.right == null) {
                result.add(str + node.val);
            }
            if (node.left != null) {
                queue.add(node.left);
                paths.add(str + node.val + "->");
            }
            if (node.right != null) {
                queue.add(node.right);
                paths.add(str + node.val + "->");
            }
        }
        return result;
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值