非递归遍历二叉树 Java

非递归实现二叉树的前序遍历

```public List preorderTraversal(TreeNode root) {
    List ret = new ArrayList<>();
    Stack stack = new Stack<>();
    stack.push(root);
    while (!stack.isEmpty()) {
        TreeNode node = stack.pop();
        if (node == null) continue;
        ret.add(node.val);
        stack.push(node.right);  // 先右后左,保证左子树先遍历
        stack.push(node.left);
    }
    return ret;
}


非递归实现二叉树的后序遍历
前序遍历为 root -> left -> right,后序遍历为 left -> right -> root。可以修改前序遍历成为 root -> right -> left,那么这个顺序就和后序遍历正好相反。
public List postorderTraversal(TreeNode root) {
    List ret = new ArrayList<>();
    Stack stack = new Stack<>();
    stack.push(root);
    while (!stack.isEmpty()) {
        TreeNode node = stack.pop();
        if (node == null) continue;
        ret.add(node.val);
        stack.push(node.left);
        stack.push(node.right);
    }
    Collections.reverse(ret);
    return ret;
}

非递归实现二叉树的中序遍历
public List inorderTraversal(TreeNode root) {
    List ret = new ArrayList<>();
    if (root == null) return ret;
    Stack stack = new Stack<>();
    TreeNode cur = root;
    while (cur != null || !stack.isEmpty()) {
        while (cur != null) {
            stack.push(cur);
            cur = cur.left;
        }
        TreeNode node = stack.pop();
        ret.add(node.val);
        cur = node.right;
    }
    return ret;
}

你可能感兴趣的:(LeetCode)