劍指offer 二叉樹映象

2021-09-26 00:07:22 字數 1266 閱讀 7310

操作給定的二叉樹,將其變換為源二叉樹的映象。

二叉樹的映象定義:源二叉樹 

8/ \

6 10

/ \ / \

5 7 9 11

映象二叉樹

8/ \

10 6

/ \ / \

11 9 7 5

交換左右節點,遍歷左節點,右節點,求映象

class treenode:

def __init__(self,item):

self.val=item

self.left=none

self.right=none

class solution:

def mirror(self,root):

if root:

root.left,root.right=root.right,root.left

if root.left:

self.mirror(root.left)

if root.right:

self.mirror(root.right)

return root

②# definition for a binary tree node.

# class treenode:

# def __init__(self, x):

# self.val = x

# self.left = none

# self.right = none

class solution:

def mirrortree(self, root: treenode) -> treenode:

if not root:

return none

root.left,root.right=root.right,root.left

self.mirrortree(root.left)

self.mirrortree(root.right)

return root

複雜度分析

時間複雜度:o(n),其中 nn 為二叉樹節點的數目。我們會遍歷二叉樹中的每乙個節點,對每個節點而言,我們在常數時間內交換其兩棵子樹。

空間複雜度:o(n)。使用的空間由遞迴棧的深度決定,它等於當前節點在二叉樹中的高度。在平均情況下,二叉樹的高度與節點個數為對數關係,即 o(\log n)。而在最壞情況下,樹形成鏈狀,空間複雜度為 o(n)

劍指offer 二叉樹映象

操作給定的二叉樹,將其變換為源二叉樹的映象。二叉樹的映象定義 源二叉樹 8 6 10 5 7 9 11 映象二叉樹 8 10 6 11 9 7 5 這道題目就是交換樹的左右節點之後,遞迴呼叫。不遞迴的方法我覺得可以考慮使用層次遍歷那樣的佇列式方法,不過太麻煩了吧。coding utf 8 class...

劍指offer 二叉樹映象

操作給定的二叉樹,將其變換為源二叉樹的映象。遞迴判斷是否為空 不為空交換左右子樹 左子樹呼叫 右子樹呼叫。兩種寫法 coding utf 8 class treenode def init self,x self.val x self.left none self.right none class ...

劍指offer 二叉樹 二叉樹的映象

操作給定的二叉樹,將其變換為源二叉樹的映象。二叉樹的映象定義 源二叉樹 8 6 10 5 7 9 11 映象二叉樹 8 10 6 11 9 7 51,交換左右子樹 2,遞迴交換左右子樹的左右子節點 package offertest title mirror description author 田...