Advertisement
1988coder

897. Increasing Order Search Tree

Feb 5th, 2019
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.00 KB | None | 0 0
  1. // LeetCode URL: https://leetcode.com/problems/increasing-order-search-tree/
  2.  
  3. // Definition for a binary tree node.
  4. class TreeNode {
  5.     int val;
  6.     TreeNode left;
  7.     TreeNode right;
  8.  
  9.     TreeNode(int x) {
  10.         val = x;
  11.     }
  12. }
  13.  
  14. /**
  15.  * Iterative Solution
  16.  *
  17.  * Time Complexity: O(N)
  18.  *
  19.  * Space Complexity: O(1)
  20.  *
  21.  * N = Number of nodes in the tree.
  22.  */
  23. class Solution1 {
  24.     public TreeNode increasingBST(TreeNode root) {
  25.         if (root == null) {
  26.             return null;
  27.         }
  28.  
  29.         TreeNode dummy = new TreeNode(0);
  30.         dummy.right = root;
  31.         TreeNode pre = dummy;
  32.         TreeNode cur = root;
  33.  
  34.         while (cur != null) {
  35.             if (cur.left != null) {
  36.                 TreeNode tmp = cur.left;
  37.                 while (tmp.right != null) {
  38.                     tmp = tmp.right;
  39.                 }
  40.                 tmp.right = cur;
  41.                 pre.right = cur.left;
  42.                 cur.left = null;
  43.                 cur = pre.right;
  44.             } else {
  45.                 pre = cur;
  46.                 cur = cur.right;
  47.             }
  48.         }
  49.  
  50.         return dummy.right;
  51.     }
  52. }
  53.  
  54. /**
  55.  * Iterative Solution
  56.  *
  57.  * Time Complexity: O(N)
  58.  *
  59.  * Space Complexity: O(Height of the tree). In worst case O(N)
  60.  *
  61.  * N = Number of nodes in the tree.
  62.  */
  63. class Solution2 {
  64.     public TreeNode increasingBST(TreeNode root) {
  65.         if (root == null) {
  66.             return null;
  67.         }
  68.  
  69.         TreeNode dummy = new TreeNode(0);
  70.         dummy.right = root;
  71.  
  72.         TreeNode[] curSolved = new TreeNode[1];
  73.         curSolved[0] = dummy;
  74.  
  75.         inorderHelper(root, curSolved);
  76.  
  77.         return dummy.right;
  78.     }
  79.  
  80.     private void inorderHelper(TreeNode node, TreeNode[] curSolved) {
  81.         if (node == null) {
  82.             return;
  83.         }
  84.         inorderHelper(node.left, curSolved);
  85.         curSolved[0].right = node;
  86.         curSolved[0] = curSolved[0].right;
  87.         node.left = null;
  88.         inorderHelper(node.right, curSolved);
  89.     }
  90. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement