Iam_Sandeep

Morris inorder preorder O(n) O(1) space traversals threaded binary tree

Apr 16th, 2022 (edited)
836
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.97 KB | None | 0 0
  1. class Solution:
  2.     def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
  3.         cur=root
  4.         ans=[]
  5.         while cur:
  6.             if cur.left:
  7.                 pred=cur.left
  8.                 while pred.right and  pred.right!=cur:
  9.                     pred=pred.right
  10.                 if pred.right==None:
  11.                     pred.right=cur
  12.                     cur=cur.left
  13.                 else:
  14.                     pred.right=None
  15.                     ans.append(cur.val)
  16.                     cur=cur.right
  17.             else:
  18.                 ans.append(cur.val)
  19.                 cur=cur.right
  20.         return ans
  21.  
  22. class Solution:
  23.     def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
  24.         cur=root
  25.         ans=[]
  26.         while cur:
  27.             if not cur.left:
  28.                 ans.append(cur.val)
  29.                 cur=cur.right
  30.             else:
  31.                 pred=cur.left
  32.                 while pred.right and pred.right!=cur:
  33.                     pred=pred.right
  34.                 if pred.right==None:
  35.                     pred.right=cur
  36.                     ans.append(cur.val)
  37.                     cur=cur.left
  38.                 else:
  39.                     pred.right=None
  40.                     cur=cur.right
  41.         return ans
  42. class Solution:
  43.     def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
  44.         ans=[]
  45.         cur=root
  46.         while cur:
  47.             if cur.right==None:
  48.                 ans.append(cur.val)
  49.                 cur=cur.left
  50.             else:
  51.                 succ=cur.right
  52.                 while succ.left and succ.left!=cur:
  53.                     succ=succ.left
  54.                 if succ.left==cur:
  55.                     succ.left=None
  56.                     cur=cur.left
  57.                 else:
  58.                     ans.append(cur.val)
  59.                     succ.left=cur
  60.                     cur=cur.right
  61.         return ans[::-1]
  62.                    
  63.                    
  64.                    
  65.        
Add Comment
Please, Sign In to add comment