Question
Can someone help me with making this code iterative? /** * Problem: Perform rotations on tree1 to make it equivalent to tree2. */ public static
Can someone help me with making this code iterative?
/** * Problem: Perform rotations on tree1 to make it equivalent to tree2. */ public static void problem(BST tree1, BST tree2) { //if root is null then we've reached the end of a branch (base case) if(tree1.root == null || tree2.root == null) { return; }
//finding the node we need to rotate to tree1's root to match 2nd tree Node match = tree1.find(tree2.getRootKey());
//loop to rotate matched node until it becomes tree1's new root or parent of the root while(match != tree1.root && match != tree1.root.parent) { //parent node of matched node we need to get to new position Node matchParent = match.parent;
//move matched node we want up the levels of tree1 //if matched node key is more than its parent then rotate parent left (which moves matched node up a level) //otherwise rotate the parent right (still moves matched node up a level) if(match.key > matchParent.key) { tree1.rotateL(matchParent); } else { tree1.rotateR(matchParent); } }
//if the matched node becomes the parent of tree1's root, in the loop above, then we need to //change it so that the matched node is the root to line up with tree2 if(match == tree1.root.parent) { tree1.root = match; }
// recursively go through left tree // new BSTs to signify left subtrees BST leftTree1 = new BST(); BST leftTree2 = new BST();
leftTree1.root = tree1.root.left; leftTree2.root = tree2.root.left; problem(leftTree1, leftTree2);
// recursively go through right tree // new BSTs to signify right subtrees BST rightTree1 = new BST(); BST rightTree2 = new BST();
rightTree1.root = tree1.root.right; rightTree2.root = tree2.root.right; problem(rightTree1, rightTree2); }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started