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 one right child.
Example:
Input: 5
/ \
1 7
Outout tree:
1
\
5
\
7
Inorder: 1 5 7
Approach
Java
import java.util.ArrayList;import java.util.Arrays;import java.util.List;public class IncreasingOrderSearchTree {public static void main(String[] args) {TreeNode root = new TreeNode(5);root.left = new TreeNode(1);root.right = new TreeNode(7);TreeNode incres = increasingBST(root);inorder(incres);System.out.println(Arrays.asList(result));}// TreeNode icreasing orderstatic TreeNode root1 = new TreeNode();// method to increasing bstprivate static TreeNode increasingBST(TreeNode root) {TreeNode temp = root1;dfs(root);return temp.right;}// dfs on treeprivate static void dfs(TreeNode root) {if (root == null)return;dfs(root.left);root1.right = new TreeNode(root.val);root1 = root1.right;dfs(root.right);}static List<Integer> result = new ArrayList<>();public static void inorder(TreeNode root) {if (root == null)return;// visit left nodeinorder(root.left);// Add root valueresult.add(root.val);// visit right nodeinorder(root.right);}}class TreeNode {int val;TreeNode left;TreeNode right;TreeNode() {}TreeNode(int val) {this.val = val;}TreeNode(int val, TreeNode left, TreeNode right) {this.val = val;this.left = left;this.right = right;}}
C++
#include <bits/stdc++.h>using namespace std;//struct for treenodestruct TreeNode{int data;TreeNode *left;TreeNode *right;TreeNode(){}TreeNode(int data){this->data=data;this->left=NULL;this->right=NULL;}};void dfs(TreeNode *&root1,TreeNode *root){if(root==NULL)return;dfs(root1,root->left);root1->right=new TreeNode(root->data);root1=root1->right;dfs(root1,root->right);}TreeNode* increasingBST(TreeNode* root){TreeNode *root1=new TreeNode();TreeNode *temp=root1;dfs(root1,root);return temp->right;}//Function to find inorder Traversal//of treevoid inorderTraversal(TreeNode *root){//Base Caseif(root==NULL)return;//visit left subtreeinorderTraversal(root->left);// visit rootcout<<root->data<<" ";//visit right subtreeinorderTraversal(root->right);}int main(){TreeNode *root=new TreeNode(5);root->left=new TreeNode(1);root->right=new TreeNode(7);TreeNode *incres=increasingBST(root);inorderTraversal(incres);return 0;}
No comments:
Post a Comment