题目描述
给定一个二叉树,返回它的中序 遍历。使用迭代方法。
思路分析
用栈来辅助,先入栈,再访问。
代码实现
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> list =new LinkedList<>();
if(root!=null){
Stack<TreeNode> stack =new Stack<>();
while (!stack.isEmpty() || root!=null){
if(root!=null){
stack.push(root);
root=root.left;
}else {
root=stack.pop();
list.add(root.val);
root=root.right;
}
}
}
return list;
}