Python演算法 如何複製二叉樹

2021-09-25 22:52:23 字數 1678 閱讀 5769

給定乙個二叉樹,複製該樹

複製一顆二叉樹,先複製其根結點,再複製左子樹,最後複製右子樹,從而複製完成;

# -*- coding:utf-8 -*-

class bitnode():

def __init__(self):

self.data = none

self.lchild = none

self.rchild = none

def creatduptree(root):

if root == none:

return none

#二叉樹根節點

duptree = bitnode()

duptree.data = root.data

#複製左子樹

duptree.lchild = creatduptree(root.lchild)

#複製右子樹

duptree.rchild = creatduptree(root.rchild)

return duptree

def printtreemidorder(root):

if root == none:

return

#遍歷root結點左子樹

if root.lchild != none:

printtreemidorder(root.lchild)

#遍歷root結點

print(root.data)

#遍歷root結點右子樹

if root.rchild != none:

printtreemidorder(root.rchild)

def constructtree():

root = bitnode()

node1 = bitnode()

node2 = bitnode()

node3 = bitnode()

node4 = bitnode()

root.data = 6

node1.data = 3

node2.data = -7

node3.data = -1

node4.data = 9

root.lchild = node1

root.rchild = node2

node1.lchild = node3

node1.rchild = node4

node2.lchild=node2.rchild=node3.lchild=node3.rchild=node4.lchild=node4.rchild=none

return root

if __name__ == "__main__":

root1 = constructtree()

root2 = creatduptree(root1)

print("原始二叉樹中序遍歷:")

printtreemidorder(root1)

print("新二叉樹中序遍歷:")

printtreemidorder(root2)

執行結果:

原始二叉樹中序遍歷:-13

96-7新二叉樹中序遍歷:-13

96-7

此方法對二叉樹進行了一次遍歷,演算法時間複雜度為o(n),此外,這種方法需要申請n個額外的儲存空間儲存新的二叉樹。

如何複製二叉樹 python

題目描述 給定乙個二叉樹根節點,複製該樹,返回新建樹的根節點。分析與解答 用給定的二叉樹的根節點root來構造新的二叉樹的方法為 首先建立新的結點duptree,然後根據root結點來構造duptree結點,最後分別用root的左右子樹來構造duptree的左右子樹。根據這個思路可以實現二叉樹的複製...

複製二叉樹

複製一棵二叉樹的非遞迴演算法 include include include using namespace std typedef struct btnode bitree bitree creat bt return t 遞迴複製,不分配空間 void copytree bitree t,bit...

python 二叉樹查詢 Python二叉樹搜尋

stack depth is initialised to 0 def find in tree node,find condition,stack depth assert stack depth max stack depth deeper than max depth stack depth ...