Introduction
Code study
It is better for me to choose one of discussion, and check in the code, and then plan to write C# solution later.
Here is the discussion link.
Most important is to read yfcheng's analysis. Plan to spend 20 minutes to read and also review the drawings. And then I will write down my own words, and make a drawing as well.
Recursive solution in Java code:
Analysis
Java code
Recursive solution in Java code:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public TreeNode upsideDownBinaryTree(TreeNode root) { | |
if(root == null || root.left == null) { | |
return root; | |
} | |
TreeNode newRoot = upsideDownBinaryTree(root.left); | |
root.left.left = root.right; // node 2 left children | |
root.left.right = root; // node 2 right children | |
root.left = null; | |
root.right = null; | |
return newRoot; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public TreeNode upsideDownBinaryTree(TreeNode root) { | |
TreeNode curr = root; | |
TreeNode next = null; | |
TreeNode temp = null; | |
TreeNode prev = null; | |
while(curr != null) { | |
next = curr.left; | |
// swapping nodes now, need temp to keep the previous right child | |
curr.left = temp; | |
temp = curr.right; | |
curr.right = prev; | |
prev = curr; | |
curr = next; | |
} | |
return prev; | |
} |
Actionable Item
I finished the blog at 6:00 AM, only 15 minutes. Will come back to work on the algorithm based on the discussion.
No comments:
Post a Comment