您的位置:首页 > 其它

Invert Binary Tree

2015-07-31 15:44 246 查看
题目:

Invert a binary tree.
4
/   \
2     7
/ \   / \
1   3 6   9

to
4
/   \
7     2
/ \   / \
9   6 3   1

解题思路:
此题就是对树的结构一些应用以及对递归的考察。解答此题时,破费一些时间,说明对树与递归还未完全 熟悉。

# Definition for a binary tree node.

# class TreeNode:

# def __init__(self, x):

# self.val = x

# self.left = None

# self.right = None

class Solution:

# @param {TreeNode} root

# @return {TreeNode}

def invertTree(self, root):

if root==None or (root.left==None and root.right==None):

return root

elif root.left!=None and root.right!=None:

root.left, root.right=self.invertTree(root.right), self.invertTree(root.left)

return root

elif root.left!=None:

root.right = self.invertTree(root.left)

root.left = None

return root

elif root.right!=None:

root.left = self.invertTree(root.right)

root.right = None

return root
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: