LeetCode 257. Binary Tree Paths

该博客讨论了如何使用前序遍历方法来找出二叉树的所有路径,并提供了具体的Java实现。博客中提到,虽然可以使用辅助函数,但其命名可能不够直观,导致递归表达式难以理解。解决方案中,当遇到叶子节点时,将当前路径添加到答案列表。在遍历过程中,分别对左子节点和右子节点进行递归操作,构建路径字符串。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

print all the paths of BT, the out put format should be: [“1->2->5”, “1->3”]

clearly, we will use the preorder, but they are not exactly the same.

I can’t think of any ways to get this problem done.

but based on the solution:
binaryTreePath(root) = searchBt(root, String path, List answer) = searchBT(root.left, path+root.val+"->", answer) searchBT((root.right, path+root.val+"->", answer) //and when it reached the end, we added the current path to our list.

class Solution {
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> list = new ArrayList<>();
        if (root == null) return list;
        helper(root, list, ""); //root, 返回集合,返回集合中的子元素
        return list;
    }
    
    private void helper(TreeNode cur, List<String> list, String path) {
        if (cur.left == null && cur.right == null) {
            list.add(path + cur.val);
            return;
        }
            
        if (cur.left != null) helper(cur.left, list, path + cur.val + "->");
        if (cur.right != null) helper(cur.right, list, path + cur.val + "->");
    }
    
    
}

有的时候 用helper函数也并不好 因为这个函数名太不直观 写递归等式的时候很难理解。
而且还有一点 root == null这个条件一定要判断。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值