栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

257. 二叉树的所有路径

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

257. 二叉树的所有路径

给定一个二叉树,返回所有从根节点到叶子节点的路径。

示例: 

第一次写出递归,记录一下

解法一:递归法

递归三步:

1.确定函数入参和返回值,入参为当前节点,和到当前节点的路径字符串,返回值为空即可

2.确定终止条件,到叶子节点的时候就可以把入参的路径字符串加到结果集合中

3.确定单层逻辑,递归当前节点的左右节点,拼接上节点值即可

class Solution {
    List res = new ArrayList<>();
    public List binaryTreePaths(TreeNode root) {
        if (root == null) {
            return res;
        }
        String s = "" + root.val;
        dfs(root,s);
        return res;
    }

    public void dfs(TreeNode root, String s) {
        if (root.right == null && root.left == null) {
            res.add(s);
        }
        if (root.left != null) {
            dfs(root.left,s + "->" + root.left.val);
        }
        if (root.right != null) {
            dfs(root.right,s + "->" + root.right.val);
        }
    }
}

解法二:迭代法

先序遍历加入节点和路径,遍历左右节点时拼接节点值,判断一下是否叶子节点即可

public List binaryTreePaths(TreeNode root) {
        List res = new ArrayList<>();
        if (root == null) {
            return res;
        }
        Stack stack = new Stack<>();
        stack.push(root);
        String s = "" + root.val;
        stack.push(s);
        while (!stack.isEmpty()) {
            String path = (String) stack.pop();
            TreeNode node = (TreeNode) stack.pop();
            if (node.right == null && node.left == null) {
                res.add(path);
            }
            if (node.right != null) {
                stack.push(node.right);
                stack.push(path + "->" + node.right.val);
            }
            if (node.left != null) {
                stack.push(node.left);
                stack.push(path + "->" + node.left.val);
            }
        }
        return res;
    } 

转载请注明:文章转载自 www.mshxw.com
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号