Not hard question. Basic idea is to use stack. Stack is a good tool for replacing loop with recursion. One thing should be aware of is "Be careful for different cases"
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
ArrayList<Integer> rslt = new ArrayList<Integer>();
if(root == null) return rslt;
LinkedList<TreeNode> stack = new LinkedList<TreeNode>();
TreeNode tmpRoot = root;
stack.push(tmpRoot);
while(!stack.isEmpty()){
while(tmpRoot.left != null){
stack.push(tmpRoot.left);
tmpRoot = tmpRoot.left;
}
TreeNode tmpNode = stack.pop();
rslt.add(tmpNode.val);
if(tmpNode.right != null){
tmpRoot = tmpNode.right;
stack.push(tmpRoot);
}
else{
if(stack.isEmpty()) break;
else{
tmpRoot = stack.peekFirst();
tmpRoot.left = null;
}
}
}
return rslt;
}
}
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!!!
Wednesday, June 11, 2014
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment