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]
.
Note: Recursive solution is trivial, could you do it iteratively?
分析:中序遍历的顺序是左右根,用堆栈迭代的方法模拟递归实现,堆栈用LinkedList实现
如果当前结点不为null,则压入堆栈,然后继续观察其左孩子;如果没有左孩子,则弹出堆栈中第一个数据,观察其右孩子。
代码:
/**
* 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> listVal = new ArrayList<Integer>();
LinkedList<TreeNode> listNode = new LinkedList<TreeNode>();
if(root == null) return listVal;
TreeNode p = root;
while(!listNode.isEmpty() || p != null){
if(p != null){
listNode.push(p);
p = p.left;
continue;
}
TreeNode t = listNode.pop();//
listVal.add(t.val);
p = t.right;
}
return listVal;
}
}