【Leetcode】257. Binary Tree Paths

题目地址:

https://leetcode.com/problems/binary-tree-paths/

返回所有从根到树叶的路径。

法1:分治法。先求左子树根到叶子节点所有路径,再求右子树根到叶子节点所有路径,最后再把根节点连上去。代码如下:

import java.util.ArrayList;
import java.util.List;

public class Solution {
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> res = new ArrayList<>();
        // 特判一下空树
        if (root == null) {
            return res;
        }
        // 如果到了叶子了,就把值加入res
        if (root.left == null && root.right == null) {
            res.add(Integer.toString(root.val));
            return res;
        }
        // 分别把左右子树根到叶子节点的路径统计出来,
        // 再把根节点加上去最后返回
        List<String> leftPaths = binaryTreePaths(root.left);
        for (String leftPath : leftPaths) {
            res.add(root.val + "->" + leftPath);
        }
        List<String> rightPaths = binaryTreePaths(root.right);
        for (String rightPath : rightPaths) {
            res.add(root.val + "->" + rightPath);
        }
        
        return res;
    }
}

时间复杂度 O ( n ) O(n) O(n),空间 O ( h ) O(h) O(h)。这里忽略了字符串的copy的时间。

法2:DFS。

import java.util.ArrayList;
import java.util.List;

public class Solution {
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> res = new ArrayList<>();
        // 特判一下空树
        if (root == null) {
            return res;
        }
        
        dfs(root, Integer.toString(root.val), res);
        return res;
    }
    // cur表示当前走到了的节点,path表示走到当前节点的时候的路径
    private void dfs(TreeNode cur, String path, List<String> res) {
    	// 如果走到了null,就什么都不做,终止
        if (cur == null) {
            return;
        }
        // 如果走到了叶子,说明当前path已经包含了一条完整路径,就将其加入res
        if (cur.left == null && cur.right == null) {
            res.add(path);
            return;
        }
        // 如果左子树不为空,就向左走一步,并将左子树根加入path
        if (cur.left != null) {
            dfs(cur.left, path + "->" + cur.left.val, res);
        }
        // 同理
        if (cur.right != null) {
            dfs(cur.right, path + "->" + cur.right.val, res);
        }
    }
}      

时空复杂度同上。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值