二叉樹的迭代遍歷(前,中,後)

2021-10-22 16:53:21 字數 1425 閱讀 4662

目錄

1、迭代方式的前序遍歷

2、迭代方式的中序遍歷

3、迭代方式的後續遍歷

class solution 

stacks = new stack();

while(root != null || !s.isempty())

root = s.peek();

s.pop();

root = root.right;

}return res;

}}

思路:採用棧作為臨時儲存,從root到左邊最後乙個,每次while都加入結果集中,遍歷到null,則開始遍歷右邊的節點,因為中間和左邊的已加入到結果集中。

複雜度:o(n),每個節點都遍歷了,空間複雜度o(h),因為棧儲存大小的與二叉樹的高度一樣。

/**

* definition for a binary tree node.

* public class treenode

* treenode(int val)

* treenode(int val, treenode left, treenode right)

* }*/class solution

stackstack = new stack();

while(root != null || !stack.isempty())

root = stack.peek();

res.add(root.val);

stack.pop();

root = root.right;

}return res;

}}

複雜度:o(n),每個節點都遍歷了,空間複雜度o(h),因為棧儲存大小的與二叉樹的高度一樣。

/**

* definition for a binary tree node.

* public class treenode

* treenode(int val)

* treenode(int val, treenode left, treenode right)

* }*/class solution

stackstack = new stack();

treenode pre = null;

while(root != null || !stack.isempty())

root = stack.peek();

if(root.right == null || root.right == pre) else

}return res;

}}

複雜度:o(n),每個節點都遍歷了,空間複雜度o(h),因為棧儲存大小的與二叉樹的高度一樣。

leetcode 二叉樹的前中後遍歷的迭代方法

題目就不用列了,遞迴法是很簡單的,但是迭代法還是有一定難度,在此記錄 前序 easy class solution return res 中序 medium class solution root s.top res.push back root val s.pop root root right ...

二叉樹的遍歷(前中後)

總體來說分為遞迴和非遞迴實現 前序遍歷 二叉樹前序遍歷dlr public static void preorder treenode rootnode 前序非遞迴實現,借助棧,先進後出 param public static void preordernonrecursive treenode r...

二叉樹的前中後層遍歷

package com.data.tree public class bitree package com.data.tree classname treetest description todo author payphone date 2018年12月24日 下午1 44 07 version...