摘要:解题思路求根节点到叶子节点的路径集合,采用深度搜索,利用递归实现。
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"]
1.解题思路
求根节点到叶子节点的路径集合,采用深度搜索,利用递归实现。
2.代码
public class Solution { Listres=new ArrayList (); public List binaryTreePaths(TreeNode root) { helper(root,new String()); return res; } private void helper(TreeNode root,String pre){ if(root==null) return; if(root.left==null&&root.right==null){ res.add(pre+root.val); return; } helper(root.left,pre+root.val+"->"); helper(root.right,pre+root.val+"->"); } }
文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。
转载请注明本文地址:https://www.ucloud.cn/yun/66265.html
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] ...
摘要:递归法复杂度时间空间递归栈空间对于二叉树思路简单的二叉树遍历,遍历的过程中记录之前的路径,一旦遍历到叶子节点便将该路径加入结果中。当遇到最小公共祖先的时候便合并路径。需要注意的是,我们要单独处理目标节点自身是最小公共祖先的情况。 Root To Leaf Binary Tree Paths Given a binary tree, return all root-to-leaf pat...
摘要:解题思路利用递归,对于每个根节点,只要左子树和右子树中有一个满足,就返回每次访问一个节点,就将该节点的作为新的进行下一层的判断。代码解题思路本题的不同点是可以不从开始,不到结束。代码当前节点开始当前节点左节点开始当前节点右节点开始 Path SumGiven a binary tree and a sum, determine if the tree has a root-to-lea...
摘要:只要我们能够有一个以某一中间路径和为的哈希表,就可以随时判断某一节点能否和之前路径相加成为目标值。 最新更新请见: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...
摘要: 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...
阅读 2944·2021-10-15 09:41
阅读 1602·2021-09-22 15:56
阅读 2078·2021-08-10 09:43
阅读 3257·2019-08-30 13:56
阅读 1736·2019-08-30 12:47
阅读 629·2019-08-30 11:17
阅读 2729·2019-08-30 11:09
阅读 2132·2019-08-29 16:19