前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode笔记:257. Binary Tree Paths

LeetCode笔记:257. Binary Tree Paths

作者头像
Cloudox
发布2021-11-23 15:11:10
1480
发布2021-11-23 15:11:10
举报
文章被收录于专栏:月亮与二进制月亮与二进制

问题:

Given a binary tree, return all root-to-leaf paths. For example, given the following binary tree:

image.png All root-to-leaf paths are: ["1->2->5", "1->3"]

大意:

给出一个二叉树,返回所有从根节点到叶子节点的路径。 比如给出下面这个二叉树:

image.png 所有从根节点到叶子节点的路径为: ["1->2->5", "1->3"]

思路:

这道题适合用递归,依次判断有没有左右叶子节点,分别去做递归,在递归中把遇到的节点值拼接到路径字符串的最后,注意要拼接“->”这个内容,直到没有左右子节点后,表示已经到了叶子节点了,就可以终止了,把这条路径的字符串添加到结果中去。

代码:

代码语言:javascript
复制
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> result = new ArrayList<String>();
        if (root == null) return result;
        
        String path = String.valueOf(root.val);
        findPath(result, root, path);
        return result;
    }
    
    public void findPath(List<String> list, TreeNode root, String path) {
        if (root.left == null && root.right == null) {
            list.add(path);
            return;
        }
        if (root.left != null) {
            StringBuffer pathBuffer = new StringBuffer(path);
            pathBuffer.append("->");
            pathBuffer.append(String.valueOf(root.left.val));
            findPath(list, root.left, pathBuffer.toString());
        } 
        if (root.right != null) {
            StringBuffer pathBuffer = new StringBuffer(path);
            pathBuffer.append("->");
            pathBuffer.append(String.valueOf(root.right.val));
            findPath(list, root.right, pathBuffer.toString());
        }
    }
}

合集:https://github.com/Cloudox/LeetCode-Record

查看作者首页

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2017/11/22 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 问题:
  • 大意:
  • 思路:
  • 代码:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档