Leetcode 257: Binary Tree Paths

问题描述:
Given the root of a binary tree, return all root-to-leaf paths in any order.
A leaf is a node with no children.

打印二叉树的路径(实际上不是打印,存在list里面)

思路:
我们需要调用一个方法,这个方法需要有以下参数:根节点,初始路径字符串,容器。
根节点是所有路径的起始点,是root
初始路径字符串是空字符串,因为一开始没有加入任何节点
容器是我们要返回的list

首先我们要加入根节点
其次,我们要判断这个根节点是不是叶子节点,如果是的话就要考虑添加进容器里;如果不是的话,说明我们会有更多的点加入目前的路径,所以我们要先添加一个"->",然后取决于哪一侧可以继续,我们可以发现子问题:即套用相同的方法只不过根节点变为这个根节点的左/右孩子(递归)

代码如下:

class Solution {
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> list=new ArrayList<>();
        constructPath(root, "", list);
        return list;
    }
    
    private void constructPath(TreeNode root, String path, List<String> list){
        //add the root
        path=path+Integer.toString(root.val);
        //if reach the leaf, add the path
        if((root.left==null)&&(root.right==null)){
            list.add(path);
        }
        //otherwise we cannot add the path, but continue adding nodes to path
        else{
            path=path+"->";
            //depends on which direcxtion it has nodes to add
            if(root.left!=null){
                constructPath(root.left, path, list);
            }
            if(root.right!=null){
                constructPath(root.right, path, list);
            }
        }
    }
}

时间复杂度: O(n), 因为每一个节点访问一遍

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值