摘要:當(dāng)你被的時候,人家問,一定要說,當(dāng)然可以啦所以,不用,怎么辦幸好,這是一道的題目,只要逐層遍歷,就可以了。所以,試一試用堆棧的做法吧記得的特點是后入先出哦
Problem
Given a binary tree, return the preorder traversal of its nodes" values.
ExampleGiven:
1 / 2 3 / 4 5
return [1,2,4,5,3].
ChallengeCan you do it without recursion?
Note當(dāng)你被challenge的時候,人家問,Can you do it without recursion? 一定要說,當(dāng)然可以啦!所以,不用recursion,怎么辦?幸好,這是一道preorder的題目,只要逐層遍歷,就可以了。所以,試一試用堆棧的做法吧!記得Stack的特點是后入先出哦!
SolutionRecursion
public class Solution { public ArrayListpreorderTraversal(TreeNode root) { ArrayList res = new ArrayList(); if (root == null) return res; helper(res, root); return res; } public void helper(ArrayList res, TreeNode root) { res.add(root.val); if (root.left != null) helper(res, root.left); if (root.right != null) helper(res, root.right); } }
Stack
public class Solution { public ArrayListpreorderTraversal(TreeNode root) { ArrayList res = new ArrayList(); Stack stack = new Stack(); if (root == null) return res; stack.push(root); while (!stack.isEmpty()) { TreeNode cur = stack.pop(); res.add(cur.val); if (cur.right != null) stack.push(cur.right); if (cur.left != null) stack.push(cur.left); } return res; } }
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請注明本文地址:http://specialneedsforspecialkids.com/yun/65921.html
摘要:做了幾道二分法的題目練手,發(fā)現(xiàn)這道題已經(jīng)淡忘了,記錄一下。這道題目的要點在于找的區(qū)間。邊界條件需要注意若或數(shù)組為空,返回空當(dāng)前進(jìn)到超出末位,或超過,返回空每次創(chuàng)建完根節(jié)點之后,要將加,才能進(jìn)行遞歸。 Construct Binary Tree from Inorder and Preorder Traversal Problem Given preorder and inorder t...
摘要:遞歸法不說了,棧迭代的函數(shù)是利用的原理,從根節(jié)點到最底層的左子樹,依次入堆棧。然后將出的結(jié)點值存入數(shù)組,并對出的結(jié)點的右子樹用函數(shù)繼續(xù)迭代。 Problem Given a binary tree, return the inorder traversal of its nodes values. Example Given binary tree {1,#,2,3}, 1 ...
Problem Given a binary tree, return the level order traversal of its nodes values. (ie, from left to right, level by level). For example:Given binary tree {3,9,20,#,#,15,7}, 3 / 9 20 / ...
Problem Given a binary tree, return the zigzag level order traversal of its nodes values. (ie, from left to right, then right to left for the next level and alternate between). Example Given binary tr...
摘要:二分法復(fù)雜度時間空間思路我們先考察先序遍歷序列和中序遍歷序列的特點。對于中序遍歷序列,根在中間部分,從根的地方分割,前半部分是根的左子樹,后半部分是根的右子樹。 Construct Binary Tree from Preorder and Inorder Traversal Given preorder and inorder traversal of a tree, constru...
閱讀 3455·2023-04-26 02:31
閱讀 3621·2021-11-23 09:51
閱讀 1286·2021-11-17 09:33
閱讀 2436·2021-11-16 11:45
閱讀 2566·2021-10-11 11:12
閱讀 2406·2021-09-22 15:22
閱讀 2712·2021-09-04 16:40
閱讀 2569·2021-07-30 15:30