Monday, January 5, 2015

[LeetCode]Binary Tree Inorder Traversal

Binary Tree Preorder Traversal中说明过,Inorder的代码基本上是一样的,只有一行的区别。
代码如下:
/**
* 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) {
List<Integer> res = new ArrayList<Integer>();
if (root == null)
return res;
TreeNode curr = root;
Stack<TreeNode> path = new Stack<TreeNode>();
while (!path.isEmpty() || curr != null) {
while (curr != null) {
path.push(curr);
curr = curr.left;
}
curr = path.pop();
res.add(curr.val);
curr = curr.right;
}
return res;
}
}


Follow up: constant space的中序遍历, Binary Search Tree Iterator

No comments:

Post a Comment