Advertisement
1988coder

156. Binary Tree Upside Down

Jan 15th, 2019
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.38 KB | None | 0 0
  1.  
  2. // Definition for a binary tree node.
  3. class TreeNode {
  4.     int val;
  5.     TreeNode left;
  6.     TreeNode right;
  7.  
  8.     TreeNode(int x) {
  9.         val = x;
  10.     }
  11. }
  12.  
  13. /**
  14.  * Recursive Solution
  15.  *
  16.  * Time Complexity: O(N)
  17.  *
  18.  * Space Complexity: O(N)
  19.  *
  20.  * N = Number nodes in the tree or the height of the tree.
  21.  */
  22. class Solution1 {
  23.     public TreeNode upsideDownBinaryTree(TreeNode root) {
  24.         if (root == null || root.left == null) {
  25.             return root;
  26.         }
  27.  
  28.         TreeNode newRoot = upsideDownBinaryTree(root.left);
  29.         root.left.left = root.right;
  30.         root.left.right = root;
  31.         root.left = null;
  32.         root.right = null;
  33.  
  34.         return newRoot;
  35.     }
  36. }
  37.  
  38. /**
  39.  * Iterative Solution
  40.  *
  41.  * Time Complexity: O(N)
  42.  *
  43.  * Space Complexity: O(1)
  44.  *
  45.  * N = Number nodes in the tree or the height of the tree.
  46.  */
  47. class Solution2 {
  48.     public TreeNode upsideDownBinaryTree(TreeNode root) {
  49.         if (root == null || root.left == null) {
  50.             return root;
  51.         }
  52.  
  53.         TreeNode cur = root;
  54.         TreeNode pre = null;
  55.         TreeNode preRight = null;
  56.  
  57.         while (cur != null) {
  58.             TreeNode next = cur.left;
  59.  
  60.             cur.left = preRight;
  61.             preRight = cur.right;
  62.  
  63.             cur.right = pre;
  64.  
  65.             pre = cur;
  66.             cur = next;
  67.         }
  68.  
  69.         return pre;
  70.     }
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement