劍指offer 二叉樹映象

2021-09-26 03:55:23 字數 1162 閱讀 5305

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

遞迴判斷是否為空;

不為空交換左右子樹;

左子樹呼叫;

右子樹呼叫。

兩種寫法:

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

# class treenode:

# def __init__(self, x):

# self.val = x

# self.left = none

# self.right = none

class solution:

# 返回映象樹的根節點

def mirror(self, root):

# write code here

if root is none:

return root

if root:

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

return self.mirror(root.left) or self.mirror(root.right) ## 這裡是or

第二種:

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

# class treenode:

# def __init__(self, x):

# self.val = x

# self.left = none

# self.right = none

class solution:

# 返回映象樹的根節點

def mirror(self, root):

# write code here

if root is none:

return root

if root:

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

self.mirror(root.left)

self.mirror(root.right)

return root #self.mirror(root.left) and self.mirror(root.right)

劍指offer 二叉樹映象

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

劍指offer 二叉樹映象

操作給定的二叉樹,將其變換為源二叉樹的映象。二叉樹的映象定義 源二叉樹 8 6 10 5 7 9 11 映象二叉樹 8 10 6 11 9 7 5交換左右節點,遍歷左節點,右節點,求映象 class treenode def init self,item self.val item self.lef...

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

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