用迭代实现二叉树先序遍历、中序遍历、后序遍历

1.先序遍历

 public List<Integer> preorderTraversal (TreeNode root) {
        List<Integer> list =new ArrayList<>();
        Deque<TreeNode> deque =new ArrayDeque<>();
        while(!deque.isEmpty()||root!=null){
            while(root!=null){
                list.add(root.val);
                deque.push(root);
                root=root.left;
            }
            root = deque.pop();
            root=root.right;
        }
        return list;
    }

2.中序遍历

 public List<Integer> inorderTraversal (TreeNode root) {
        List<Integer> list =new ArrayList<>();
        Deque<TreeNode> deque =new ArrayDeque<>();
        while(!deque.isEmpty()||root!=null){
            while(root!=null){
                deque.push(root);
                root=root.left;
            }
            root = deque.pop();
            list.add(root.val);
            root=root.right;
        }
        return list;
    }        

3.后序遍历

  public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> list =new ArrayList<>();
        Deque<TreeNode> deque =new ArrayDeque<>();
        while(!deque.isEmpty()||root!=null){
            while(root!=null){
                list.add(root.val);
                deque.push(root);
                root=root.right;
            }
          root = deque.pop();
          root=root.left;
        }
        Collections.reverse(list);
        return list;
    }

 

posted @ 2022-03-12 19:29  Eric_muyi  阅读(66)  评论(0)    收藏  举报