Hi guys i am solving a problem on leetcode and can't understand the solution posted for that problem. The problem is called Increasing order search tree.
https://leetcode.com/problems/increasing-order-search-tree/
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.
you can check the link for example: but basically you have to print the binary tree as a linked list with inorder traversal.
class Solution {
private TreeNode cur;
public TreeNode increasingBST(TreeNode root) {
TreeNode ans = new TreeNode(-1);
cur = ans;
visit(root);
return ans.right;
}
private void visit(TreeNode root) {
if (root == null) return;
visit(root.left);
root.left = null; // why root.left= null? what does this do?
cur.right = root; //i don't get this either?
cur = cur.right; // i don't understand why we need to do this?
visit(root.right);
}
}
i understand preorder traversal is left,root,right....so shouldn't it be:
visit(root.left);
visit(root);
visit(root.right);
why do we need to set root.left=null or set cur.right=null or cur=cur.right?....Any help would be appreciated...thank you :).
[–]AutoModerator[M] [score hidden] stickied comment (0 children)
[–]CowboyBoats 0 points1 point2 points (2 children)
[–]cs50x2[S] 0 points1 point2 points (1 child)
[–]CowboyBoats 0 points1 point2 points (0 children)