题目描述:
Given a binary tree, return the inorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3}
,
1 \ 2 / 3
return [1,3,2]
.
解题思路:
使用栈。从根节点开始迭代循环访问,将节点入栈,并循环将左子树入栈。如果当前节点为空,则弹出栈顶节点,也就是当前节点的父节点,并将父节点的值加入到list中,然后选择右节点作为循环的节点,依次循环。
代码如下:
/**
* Definition for a binary tree node.
* 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> ();
Stack<TreeNode> stack = new Stack<TreeNode> ();
TreeNode cur = root;
while(cur != null || !stack.empty()){
while(cur != null){
stack.push(cur);
cur = cur.left;
}
cur =stack.pop();
res.add(cur.val);
cur = cur.right;
}
return res;
}
}