题目描述

给出一棵二叉树,返回这棵树的中序遍历
例如:
给出的二叉树为{1,#,2,3},

1↵ ↵ 2↵ /↵ 3↵
返回[1,3,2].

备注:递归的解法太没有新意了,你能用迭代的方法来解这道题吗?

代码

思路:迭代

  1. public ArrayList<Integer> inorderTraversal (TreeNode root) {
  2. // write code here
  3. ArrayList<Integer> arr = new ArrayList<Integer>();
  4. if(root==null)return arr;
  5. Stack<TreeNode> stack = new Stack<TreeNode>();
  6. while(!stack.isEmpty()||root!=null) {
  7. while(root!=null) {
  8. stack.push(root);
  9. root = root.left;
  10. }
  11. root = stack.pop();
  12. arr.add(root.val);
  13. root = root.right;
  14. }
  15. return arr;
  16. }