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

leetcode257 Binary Tree Paths

作者头像
用户1665735
发布2018-06-20 16:15:36
3450
发布2018-06-20 16:15:36
举报
文章被收录于专栏:kevindroidkevindroid

题目

Given a binary tree, return all root-to-leaf paths.

For example, given the following binary tree:

代码语言:javascript
复制
   1
 /   \
2     3
 \
  5

All root-to-leaf paths are: [“1->2->5”, “1->3”] 需要得到所有从根到叶子结点的路径。

解题思路

既然是得到路径,那么很自然的想到使用深度优先遍历(DFS),DFS在二叉树中对应的就是前序遍历,然后用一个ArrayList保存访问过的节点,就可以了。

代码语言:javascript
复制
public class leetcode257 {
    private ArrayList<Integer> record = new ArrayList<>();
    private List<String> res = new ArrayList<>();

    public List<String> binaryTreePaths(TreeNode root) {
        helper(root);
        return res;
    }

    private void helper(TreeNode node) {
        if (node != null) {
            //节点加入记录
            record.add(node.val);
            helper(node.left);
            helper(node.right);
            if (node.left == null && node.right == null) {
                //叶子结点,打印输出记录里所有节点.
                String temp = "";
                for (int i = 0; i < record.size(); i++) {
                    if (i == 0) temp += record.get(i);
                    else
                        temp = temp + "->" + record.get(i);
                }
                res.add(temp);
            }
            //此时,该节点左右子树都已经打印输出完毕,可以从记录中删除
            record.remove(record.size() - 1);
        }
    }
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017年05月05日,如有侵权请联系 cloudcommunity@tencent.com 删除

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

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

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

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