资讯专栏INFORMATION COLUMN

Binary Tree Paths

李增田 / 2078人阅读

摘要:解题思路求根节点到叶子节点的路径集合,采用深度搜索,利用递归实现。

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

For example, given the following binary tree:

</>复制代码

  1. 1
  2. /
  3. 2 3
  4. 5

All root-to-leaf paths are:

</>复制代码

  1. ["1->2->5", "1->3"]

1.解题思路

求根节点到叶子节点的路径集合,采用深度搜索,利用递归实现。

2.代码

</>复制代码

  1. public class Solution {
  2. List res=new ArrayList();
  3. public List binaryTreePaths(TreeNode root) {
  4. helper(root,new String());
  5. return res;
  6. }
  7. private void helper(TreeNode root,String pre){
  8. if(root==null) return;
  9. if(root.left==null&&root.right==null){
  10. res.add(pre+root.val);
  11. return;
  12. }
  13. helper(root.left,pre+root.val+"->");
  14. helper(root.right,pre+root.val+"->");
  15. }
  16. }

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/66265.html

相关文章

  • Leetcode[257] Binary Tree Paths

    LeetCode[257] Binary Tree Paths Given a binary tree, return all root-to-leaf paths. For example, given the following binary tree: 1 / 2 3 5 All root-to-leaf paths are:[1->2->5, 1->3] ...

    liujs 评论0 收藏0
  • [Leetcode] Binary Tree Paths 二叉树路径

    摘要:递归法复杂度时间空间递归栈空间对于二叉树思路简单的二叉树遍历,遍历的过程中记录之前的路径,一旦遍历到叶子节点便将该路径加入结果中。当遇到最小公共祖先的时候便合并路径。需要注意的是,我们要单独处理目标节点自身是最小公共祖先的情况。 Root To Leaf Binary Tree Paths Given a binary tree, return all root-to-leaf pat...

    Vicky 评论0 收藏0
  • [Leetcode-Tree] Path Sum I II III

    摘要:解题思路利用递归,对于每个根节点,只要左子树和右子树中有一个满足,就返回每次访问一个节点,就将该节点的作为新的进行下一层的判断。代码解题思路本题的不同点是可以不从开始,不到结束。代码当前节点开始当前节点左节点开始当前节点右节点开始 Path SumGiven a binary tree and a sum, determine if the tree has a root-to-lea...

    notebin 评论0 收藏0
  • [Leetcode] Path Sum I & II & III 路径和1,2,3

    摘要:只要我们能够有一个以某一中间路径和为的哈希表,就可以随时判断某一节点能否和之前路径相加成为目标值。 最新更新请见:https://yanjia.me/zh/2019/01/... Path Sum I Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that addin...

    caiyongji 评论0 收藏0
  • [LeetCode] Path Sum (I & II & III)

    摘要: 112. Path Sum Problem Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum. Note: A leaf is a node...

    张金宝 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<