訓練營第四天 二叉樹

2021-09-10 08:52:00 字數 2755 閱讀 5171

一、基礎知識

二叉樹:二叉樹是乙個連通的無環圖,並且每乙個頂點的度不大於3。有根二叉樹還要滿足根結點的度不大於2。有了根結點之後,每個頂點定義了唯一的父結點,和最多2個子結點。然而,沒有足夠的資訊來區分左結點和右結點。如果不考慮連通性,允許圖中有多個連通分量,這樣的結構叫做森林

遍歷:遍歷是對樹的一種最基本的運算,所謂遍歷二叉樹,就是按一定的規則和順序走遍二叉樹的所有結點,使每乙個結點都被訪問一次,而且只被訪問一次。由於二叉樹是非線性結構,因此,樹的遍歷實質上是將二叉樹的各個結點轉換成為乙個線性序列來表示。

設l、d、r分別表示遍歷左子樹、訪問根結點和遍歷右子樹, 則對一棵二叉樹的遍歷有三種情況:dlr(稱為先根次序遍歷),ldr(稱為中根次序遍歷),lrd (稱為後根次序遍歷)。

先序遍歷:首先訪問根,再先序遍歷左(右)子樹,最後先序遍歷右(左)子樹

中序遍歷:首先中序遍歷左(右)子樹,再訪問根,最後中序遍歷右(左)子樹

後序遍歷:首先後序遍歷左(右)子樹,再後序遍歷右(左)子樹,最後訪問根

二、98-驗證二叉搜尋樹

**:

# definition for a binary tree node.

# class treenode(object):

# def __init__(self, x):

# self.val = x

# self.left = none

# self.right = none

class solution(object):

def isvalidbst(self, root):

""":type root: treenode

:rtype: bool

"""inorder = self.inorder(root)

return inorder == list(sorted(set(inorder)))

def inorder(self, root):

if root is none:

return

return self.inorder(root.left) + [root.val] + self.inorder(root.right)

執行結果:

三、102.-二叉樹的層次遍歷

**:

# definition for a binary tree node.

# class treenode(object):

# def __init__(self, x):

# self.val = x

# self.left = none

# self.right = none

class solution(object):

def levelorder(self, root):

""":type root: treenode

:rtype: list[list[int]]

"""if(root==none):

return

node=

if(root):

ans=

while(node):

nodeval=

s=len(node)

for i in range(s):

nodepop=node.pop(0)

if(nodepop.left):

if(nodepop.right):

return ans

執行結果:

四、107-二叉樹的層次遍歷 ii

**:

# definition for a binary tree node.

# class treenode(object):

# def __init__(self, x):

# self.val = x

# self.left = none

# self.right = none

class solution(object):

def levelorderbottom(self, root):

""":type root: treenode

:rtype: list[list[int]]

"""if root is none:

return

res=[[root.val]]

roots=[[root]]

i=0l=len(roots[i])

while l>0:

tem=

t=for j in roots[i]:

if j.left:

if j.right:

if len(t)>0:

i+=1

l=len(tem)

return res[::-1]

執行結果:

ESC七天訓練營 第四天

管理終端putty 檔案傳輸filezilla 在putty中執行 國內伺服器 bash 安裝一直點下一步即可成功安裝 常 命令 ccaa 進 ccaa操作界 ccaa status 檢視ccaa運 狀態 ccaa stop 停 ccaa ccaa start 啟動ccaa ccaa restart...

資料結構與演算法之二叉樹訓練營

public inttreedepth treenode root public treelinknode getnext treelinknode node return right while node.next null node node.next return null public tr...

鄧俊輝 演算法訓練營練習 二叉排序樹

先序遍歷 輸出自己 左子樹 右子樹 中序遍歷 輸出左子樹 自己 右子樹 include using namespace std struct node t 10000 root代表根節點 cnt代表二叉樹大小 int root,cnt 建樹 int insert int v,int x t x lc...