Increasing Order Search Tree - Tree - Easy - LeetCode
💻 coding

Increasing Order Search Tree - Tree - Easy - LeetCode

1 min read 208 words
1 min read
ShareWhatsAppPost on X
  • 1The task involves rearranging a binary search tree into a right-skewed tree with no left children.
  • 2The leftmost node of the original tree becomes the new root after rearrangement.
  • 3The algorithm operates with a time complexity of O(n) and a space complexity of O(height).

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"The task involves rearranging a binary search tree into a right-skewed tree with no left children."

Increasing Order Search Tree - Tree - Easy - LeetCode

Given a binary search tree, rearrange the tree in in-order so that the leftmost node in the tree is now the root of the tree, and every node has no left child and only 1 right child.

Example 1: Input: [5,3,6,2,4,null,8,1,null,null,null,7,9]

5 / \ 3 6 / \ \ 2 4 8 / / \ 1 7 9

Output: [1,null,2,null,3,null,4,null,5,null,6,null,7,null,8,null,9]

1 \ 2 \ 3 \ 4 \ 5 \ 6 \ 7 \ 8 \ 9

Constraints:

The number of nodes in the given tree will be between 1 and 100. Each node will have a unique integer value from 0 to 1000.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 * public int val;
 * public TreeNode left;
 * public TreeNode right;
 * public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
 * this.val = val;
 * this.left = left;
 * this.right = right;
 * }
 * }
 */
public class Solution {
 TreeNode prev=null;
 TreeNode head=null;
 public TreeNode IncreasingBST(TreeNode root) {
 if(root==null){
 return null;
 }
 IncreasingBST(root.left);
 if(prev != null){
 prev.left = null;
 prev.right = root;
 }
 
 if(head==null){
 head = root;
 }
 prev = root; 
 IncreasingBST(root.right);
 
 return head;
 }
}

Time Complexity: O(n)

Space Complexity: O(height)

height is the height of tree.

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

sumitc91

Published on 9 October 2020 · 1 min read · 208 words

Part of AskGif Blog · coding

You might also like