Advertisement
lichenran1234

TreeTraverseConstSpace

Apr 11th, 2021
272
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.87 KB | None | 0 0
  1. def inOrderTraverse(root):
  2.     if root is None:
  3.         return []
  4.    
  5.     result = []
  6.     cur_node = root
  7.    
  8.     visit_left = True
  9.     while True:
  10.         if visit_left:
  11.             visit_left = False
  12.             while cur_node.left is not None:
  13.                 cur_node = cur_node.left
  14.         else:
  15.             result.append(cur_node.val)
  16.             if cur_node.right is not None:
  17.                 visit_left = True
  18.                 cur_node = cur_node.right
  19.             else:
  20.                 visit_left = False
  21.                 target_parent = None
  22.                 while cur_node.parent is not None:
  23.                     if cur_node.parent.left == cur_node:
  24.                         target_parent = cur_node.parent
  25.                         break
  26.                     cur_node = cur_node.parent
  27.                 if target_parent is None:
  28.                     break
  29.                 cur_node = target_parent
  30.     return result
  31.  
  32. def inOrderReverseTraverse(root):
  33.     if root is None:
  34.         return []
  35.    
  36.     result = []
  37.     cur_node = root
  38.    
  39.     visit_right = True
  40.     while True:
  41.         if visit_right:
  42.             visit_right = False
  43.             while cur_node.right is not None:
  44.                 cur_node = cur_node.right
  45.         else:
  46.             result.append(cur_node.val)
  47.             if cur_node.left is not None:
  48.                 visit_right = True
  49.                 cur_node = cur_node.left
  50.             else:
  51.                 visit_right = False
  52.                 target_parent = None
  53.                 while cur_node.parent is not None:
  54.                     if cur_node.parent.right == cur_node:
  55.                         target_parent = cur_node.parent
  56.                         break
  57.                     cur_node = cur_node.parent
  58.                 if target_parent is None:
  59.                     break
  60.                 cur_node = target_parent
  61.     return result
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement