Skip to content

Instantly share code, notes, and snippets.

@chenjie
Created May 17, 2019 00:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chenjie/eb24769d2a3bb1d2f50c8a14ef7aedb9 to your computer and use it in GitHub Desktop.
Save chenjie/eb24769d2a3bb1d2f50c8a14ef7aedb9 to your computer and use it in GitHub Desktop.
Mirror/Deep copy of a Binary Tree/BST without recursion (iterative approach)
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param root: The root of binary tree
@return: root of new tree
"""
def cloneTree(self, root):
# write your code here
if root is None:
return None
oriq = [root]
res = TreeNode(root.val)
newq = [res]
while len(newq) > 0:
new = newq.pop()
ori = oriq.pop()
new_left = None
new_right = None
if ori.left is not None:
new_left = TreeNode(ori.left.val)
new.left = new_left
oriq.insert(0, ori.left)
newq.insert(0, new_left)
if ori.right is not None:
new_right = TreeNode(ori.right.val)
new.right = new_right
oriq.insert(0, ori.right)
newq.insert(0, new_right)
return res
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment