※【回溯】【深度优先前序】Leetcode 257. 二叉树的所有路径

※【回溯】【深度优先前序】Leetcode 257. 二叉树的所有路径

---------------🎈🎈257. 二叉树的所有路径 题目链接🎈🎈-------------------

在这里插入图片描述

解法0 迭代法

解法1 深度优先 前序

时间复杂度O(N)
空间复杂度O(N)


/**
 * 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 {
    List<String> result = new ArrayList<>();
    public List<String> binaryTreePaths(TreeNode root) {
        helper(root,"");
        return result;
    }
    public void helper(TreeNode root, String s){
        // 前序 中左右
        
        if(root == null) return;
        if(root.left == null && root.right == null){
            result.add(s + root.val);
        }

        String temp = s + root.val + "->";
        helper(root.left,temp);
        helper(root.right,temp);
    }
} 

解法2 深度优先 前序 添加了StringBulider

深度优先遍历 添加了StringBulider替代字符串拼接提升效率
toString()转化为String
.append()添加元素

时间复杂度O(N)
空间复杂度O(N)

/**
 * 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 {
    List<String> result = new ArrayList<>();
    public List<String> binaryTreePaths(TreeNode root) {
        helper(root,"");
        return result;
    }
    public void helper(TreeNode root, String s){
        // 前序 中左右  使用StringBuilder提升效率
        
        // 停止条件
        if(root == null) return;
        if(root.left == null && root.right == null){ // 如果遍历到叶子节点,那么就在result中添加该路径(该路径就是前面得到的s+当前值)
            result.add(new StringBuilder(s).append(root.val).toString());
            return;
        }

        String temp = new StringBuilder(s).append(root.val).append("->").toString();  // 中 当前路径 s 加上当前节点值和箭头 "->" 的组合

        helper(root.left, temp);  // 左
        helper(root.right, temp); // 右
    }
}
  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值