LeetCode230131_143、257. 二叉树的所有路径

给你一个二叉树的根节点 root ,按 任意顺序 ,返回所有从根节点到叶子节点的路径。

叶子节点 是指没有子节点的节点。

图1 二叉树的所有路径

示例 1:
输入:root = [1,2,3,null,5]
输出:["1->2->5","1->3"]

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/binary-tree-paths
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题解一、递归求法,左右节点均为空时进行字符串拼接加入结果列表,不为空,继续递归左右节点进行字符串拼接后的参数变化。

class Solution {
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> res = new ArrayList<>();
        String path = "";
        dfs(root, path, res);
        return res;
    }
    public void dfs(TreeNode root, String path, List<String> res) {
        if (root == null) return;
        if (root.left == null && root.right == null) {
            res.add(path + root.val);
        }
        dfs(root.left, path + root.val + "->", res);
        dfs(root.right, path + root.val + "->", res);
    }
}

题解二、层序遍历直至遇到左右节点为空,进行拼接,不为空时,前面路径 + "->" + 左(右)节点值

class Solution {
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> res = new ArrayList<>();
        if (root == null) return res;
        Queue<Object> queue = new LinkedList<>();
        queue.offer(root);
        queue.offer("" + root.val);
        while (!queue.isEmpty()) {
            TreeNode node = (TreeNode) queue.poll();    
            String path = (String) queue.poll();
            if (node.left == null && node.right == null) {
                res.add(path);
            }
            if (node.left != null) {
                queue.offer(node.left);
                queue.offer(path + "->" + node.left.val);
            }
            if (node.right != null) {
                queue.offer(node.right);
                queue.offer(path + "->" + node.right.val);
            }
        }
        return res;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值