LintCode Q375 Clone Binary Tree in Python

  • Jinhai ZHOU
  • 3 Minutes
  • 2016年11月17日
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
this.val = val
this.left, this.right = None, None
"""
class Solution:
"""
@param {TreeNode} root: The root of binary tree
@return {TreeNode} root of new tree
"""
def cloneTree(self, root):
# Write your code here
if root is None:
return
root_copy = TreeNode(root.val)
self.inOrderCopy(root, root_copy)
return root_copy
def inOrderCopy(self, node, node_copy):
if node is None:
return
if node.left:
left_copy = TreeNode(node.left.val)
node_copy.left = left_copy
self.inOrderCopy(node.left, node_copy.left)
if node.right:
right_copy = TreeNode(node.right.val)
node_copy.right = right_copy
self.inOrderCopy(node.right, node_copy.right)
知识共享许可协议
本作品采用知识共享署名-相同方式共享 4.0 国际许可协议进行许可。