LeetCode(257):二叉树的所有路径

博客围绕 LeetCode 257 题“二叉树的所有路径”展开。指出当前处理二叉树问题常采用深度优先和广度优先遍历,看到此题首先会想到深度优先遍历。题解部分介绍了深度优先遍历的递归实现和利用队列的广度优先遍历方法。

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

LeetCode(257):二叉树的所有路径

题目描述

在这里插入图片描述
目前处理二叉树的问题,多在进行二叉树的深度优先遍历和广度优先遍历。看到这个题目的第一瞬间,想到的就是深度优先遍历。从根节点走到叶子节点。

题解

深度优先遍历(递归实现)

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> result = new LinkedList<>();
        if(root == null){
            return result;
        }
        path(root,root.val+"",result);
        return result;
    }
    public static void path(TreeNode root,String s,List<String> result){
        if(root.left == null && root.right == null){
            result.add(s);
            return;
        }
        if(root.left != null){
            path(root.left,s+"->"+root.left.val,result);
        }
         if(root.right != null){
            path(root.right,s+"->"+root.right.val,result);
        }
    }

}

广度优先遍历(队列)

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<String> binaryTreePaths(TreeNode root) {
        // 广度优先遍历,使用队列。设计一个Tree,其中一项保存path
        List<String> result = new LinkedList<>();
        if(root == null){
            return result;
        }
        Queue<Tree> queue = new LinkedList<>();
        Tree tree = new Tree(root,root.val+"");
        queue.offer(tree);
        while(!queue.isEmpty()){
            tree = queue.poll();
            if(tree.treeNode.left == null && tree.treeNode.right == null){
                result.add(tree.path);
            }
            if(tree.treeNode.right != null){
                queue.offer(new Tree(tree.treeNode.right,tree.path+"->"+tree.treeNode.right.val));
            }
             if(tree.treeNode.left != null){
                queue.offer(new Tree(tree.treeNode.left,tree.path+"->"+tree.treeNode.left.val));
            }
        }
        return result;
    }  
}
class Tree{
    TreeNode treeNode;
    String path;
    Tree(TreeNode treeNode,String path) { 
        this.treeNode = treeNode;
        this.path = path; 
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值