二叉樹的遍歷

2022-09-11 22:51:31 字數 3941 閱讀 4849

二叉樹的前中後序遍歷是面試考察中乙個重要的點。而遞迴方法是最簡單實現的,所以要信手拈來。非遞迴方法更要加以掌握。前序就是根-左-右,中序是左-根-右,後序是左-右-根。

有兩種通用的遍歷樹的策略:

深度優先搜尋(dfs)

在這個策略中,我們採用深度作為優先順序,以便從跟開始一直到達某個確定的葉子,然後再返回根到達另乙個分支。

深度優先搜尋策略又可以根據根節點、左孩子和右孩子的相對順序被細分為前序遍歷,中序遍歷和後序遍歷。

寬度優先搜尋(bfs)

我們按照高度順序一層一層的訪問整棵樹,高層次的節點將會比低層次的節點先被訪問到。

非遞迴,用佇列實現(其實自己想了會能不能用遞迴結果自己不會。。。

看了下題解,它的遞迴實現其實用了深度優先。

class solution:

def levelorder(self, root: treenode) -> list[list[int]]:

if root==none:

return

result = [[root.val]]

quene = [(root,1)]

while(quene):

root,count = quene.pop(0)

if root.left:

if count+1>len(result):

else:

if root.right:

if count+1>len(result):

else:

return result

題目描述:鏈結 

非遞迴採用兩層迴圈:按照根節點左子樹順序壓棧,然後再改變指標,對右子樹採用同樣的方法

class solution:

def inordertr**ersal(self, root: treenode) -> list[int]:

result =

stack =

if root==none:

return

while(stack or root!=none):

while(root!=none):

root = root.left

root = stack.pop()

root = root.right

return result

class solution:

def postordertr**ersal(self, root: treenode) -> list[int]:

result =

if root==none:

return result

self.posthelper(result,root)

return result

def posthelper(self,result,root):

if root==none:

return

self.posthelper(result,root.left)

self.posthelper(result,root.right)

class solution:

def postordertr**ersal(self, root: treenode) -> list[int]:

result =

stack =

pre = none

if root==none:

return result

while(stack or root!=none):

while(root!=none):

root = root.left

root = stack[-1]

if root.right==none or root.right==pre:

root = stack.pop()

pre = root

root = none

else:

root = root.right

return result

雙棧法前序遍歷比較簡單,因為是先訪問根

1.用乙個棧實現 根->右->左 的遍歷

2.用另乙個棧將遍歷順序反過來,使之變成 左->右->根

實現**:

class solution:

def postordertr**ersal(self, root: treenode) -> list[int]:

result =

stack1 = [root,]

stack2 =

if root == none:

return

while(stack1):

root = stack1.pop()

if root.left!=none:

if root.right!=none:

while(stack2):

root = stack2.pop()

return result

def postordertr**ersal(self, root: treenode) -> list[int]:

result =

stack1 = [root,]

stack2 =

if root == none:

return

while(stack1):

root = stack1.pop()

result.insert(0,root.val)

if root.left!=none:

if root.right!=none:

return result

二叉樹的遍歷 二叉樹遍歷與儲存

在資料結構中,二叉樹是非常重要的結構。例如 資料庫中經常用到b 樹結構。那麼資料庫是如何去單個查詢或者範圍查詢?首先得理解二叉樹的幾種遍歷順序 先序 中序 後序 層次遍歷。先序 根節點 左子樹 右子樹 中序 左子樹 根節點 右子樹 後序 左子樹 右子樹 根節點 按層級 class node if c...

構建二叉樹 遍歷二叉樹

陣列法構建二叉樹 public class main public static void main string args 用陣列的方式構建二叉樹 public static void createbintree 把linkedlist集合轉成二叉樹的形式 for int j 0 j 最後乙個父節...

玩轉二叉樹(二叉樹的遍歷)

時間限制 400 ms 記憶體限制 65536 kb 長度限制 8000 b 判題程式 standard 作者 陳越 給定一棵二叉樹的中序遍歷和前序遍歷,請你先將樹做個鏡面反轉,再輸出反轉後的層序遍歷的序列。所謂鏡面反轉,是指將所有非葉結點的左右孩子對換。這裡假設鍵值都是互不相等的正整數。輸入格式 ...