This problem is quite easy, but I got stuck in some trivial part. I will talk about it latter. First, let us focus on my algorithm for this problem. According to the given example, we can know that to flatten one tree is to flatten the root.left first, then add root.right to be right child of the rightmost node of root.left, finally flatten root.right. Obviously, this is a recursion problem. For root with different cases, different actions should be taken, which can be known from comments for code.
Then, one thing I really should be aware is that a function cannot make change to one object if this object is "pointed" to a new one. In this case, object is not like "pointer" any more. Sorry about using the term "pointer", since I started my coding life using C. I feel comfortable when I consider object as pointer, because they seem same, from the point of "change value of it in the called function, the value of this variable is also changed in calling function.", but actually there are many differences.
HOWEVER, this opinion is changed since I test the following code:
public void printTree(TreeNode root){
root = root.right;
}
I passed root(1), with left(2) and right child (3), into this method in main function, and the result shows that in main function, value of root is NOT affected.
After some tests, I realize that value of root is changed only when the code inside pritnTree is "root.val = 8".
So the conclusion we may make is if object's attributes or contents are changed, the change will be reflected in calling function, if it gets "pointed" to another object, i.e. the address stored in this object is changed, then this change is not reflected.
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public void flatten(TreeNode root) {
//TreeNode rightMostNode = root;
flatten1(root);
}
public TreeNode flatten1(TreeNode root) {
if(root == null) return null;
// if(root.left!=null){
TreeNode rightMostNode = flatten1(root.left);
// }
if(root.right != null && root.left !=null){
TreeNode tmpNode = root.right;
root.right = root.left;
rightMostNode.right = tmpNode;
root.left =null;
}
if(root.right == null && root.left !=null){
root.right = root.left;
root.left =null;
}
if(root.right == null && root.left ==null){
rightMostNode = root;
return rightMostNode;
}
return flatten1(root.right);
}
}
Hello, welcome to Yizhe's Blog. I am Yizhe Liu, graduated from University of Arizona, with Master degree, major in Electrical and Computer Engineering. Actually, I am software guy. In my blog, many posts are about the Leetcode questions. I will post my ideas and implementations, which are accepted by Leetcode. If you have different opinions, please leave comment. I am happy to discuss with you. So lets start rocking them!!!
Tuesday, May 27, 2014
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment