94.中序遍历

我们使用栈模拟递归,回忆二叉树的中序遍历过程,先把根和他的左子树加入栈中,如果为空就出栈,将出栈的节点值加入结果集,再把右子树加入栈中,重复之前的过程。

  1. List<Integer> res=new LinkedList<>();
  2. if(root==null) return res;
  3. Deque<TreeNode> stack=new ArrayDeque<>();
  4. while(root!=null||!stack.isEmpty()){
  5. if(root!=null){
  6. stack.offerLast(root);
  7. root=root.left;
  8. }else{
  9. root=stack.pollLast();
  10. res.add(root.val);
  11. root=root.right;
  12. }
  13. }
  14. return res;
  15. }