Binary Tree Inorder Traversal
本代码由九章算法编辑提供。没有版权欢迎转发。
- 九章算法致力于帮助更多中国人找到好的工作,教师团队均来自硅谷和国内的一线大公司在职工程师。
- 现有的面试培训课程包括:九章算法班,系统设计班,BAT国内班
- 更多详情请见官方网站:http://www.jiuzhang.com/
Definition of TreeNode:
public class TreeNode {
public int val;
public TreeNode left, right;
public TreeNode(int val) {
this.val = val;
this.left = this.right = null;
}
}
public class Solution {
/**
* @param root: The root of binary tree.
* @return: Inorder in ArrayList which contains node values.
*/
public ArrayList<Integer> inorderTraversal(TreeNode root) {
Stack<TreeNode> stack = new Stack<TreeNode>();
ArrayList<Integer> result = new ArrayList<Integer>();
TreeNode curt = root;
while (curt != null || !stack.empty()) {
while (curt != null) {
stack.add(curt);
curt = curt.left;
}
curt = stack.peek();
stack.pop();
result.add(curt.val);
curt = curt.right;
}
return result;
}
}