摘要:解題思路求根節(jié)點(diǎn)到葉子節(jié)點(diǎn)的路徑集合,采用深度搜索,利用遞歸實(shí)現(xiàn)。
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.解題思路
求根節(jié)點(diǎn)到葉子節(jié)點(diǎn)的路徑集合,采用深度搜索,利用遞歸實(shí)現(xiàn)。
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+"->"); } }
文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請(qǐng)注明本文地址:http://systransis.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] ...
摘要:遞歸法復(fù)雜度時(shí)間空間遞歸??臻g對(duì)于二叉樹思路簡單的二叉樹遍歷,遍歷的過程中記錄之前的路徑,一旦遍歷到葉子節(jié)點(diǎn)便將該路徑加入結(jié)果中。當(dāng)遇到最小公共祖先的時(shí)候便合并路徑。需要注意的是,我們要單獨(dú)處理目標(biāo)節(jié)點(diǎn)自身是最小公共祖先的情況。 Root To Leaf Binary Tree Paths Given a binary tree, return all root-to-leaf pat...
摘要:解題思路利用遞歸,對(duì)于每個(gè)根節(jié)點(diǎn),只要左子樹和右子樹中有一個(gè)滿足,就返回每次訪問一個(gè)節(jié)點(diǎn),就將該節(jié)點(diǎn)的作為新的進(jìn)行下一層的判斷。代碼解題思路本題的不同點(diǎn)是可以不從開始,不到結(jié)束。代碼當(dāng)前節(jié)點(diǎn)開始當(dāng)前節(jié)點(diǎn)左節(jié)點(diǎn)開始當(dāng)前節(jié)點(diǎn)右節(jié)點(diǎn)開始 Path SumGiven a binary tree and a sum, determine if the tree has a root-to-lea...
摘要:只要我們能夠有一個(gè)以某一中間路徑和為的哈希表,就可以隨時(shí)判斷某一節(jié)點(diǎn)能否和之前路徑相加成為目標(biāo)值。 最新更新請(qǐng)見: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...
閱讀 2980·2021-10-15 09:41
閱讀 1636·2021-09-22 15:56
閱讀 2113·2021-08-10 09:43
閱讀 3288·2019-08-30 13:56
閱讀 1793·2019-08-30 12:47
閱讀 662·2019-08-30 11:17
閱讀 2780·2019-08-30 11:09
閱讀 2201·2019-08-29 16:19