欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Given a binary tree, return the postorder traversal of its nodes' values.非递归后续遍历

程序员文章站 2022-05-20 14:05:44
...

Given a binary tree, return the postorder traversal of its nodes’ values.

For example:

Given binary tree{1,#,2,3},
1
\
2
/
3

return[3,2,1].
Note: Recursive solution is trivial, could you do it iteratively?
注意:递归解决方案是微不足道的,你能反复迭代吗?
非递归方式实现树的后序遍历
后序遍历递归定义:先左子树,后右子树,再根节点。
后序遍历的难点在于:需要判断上次访问的节点是位于左子树,还是右子树。
若是位于左子树,则需跳过根节点,先进入右子树,再回头访问根节点;
若是位于右子树,则直接访问根节点。

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
import java.util.*;
public class Solution {
    public ArrayList<Integer> postorderTraversal(TreeNode root) {
        ArrayList<Integer> result = new ArrayList<>();
        if(root == null)
            return result;
        Stack<TreeNode> s = new Stack<>();
        //curr移到左子树的最下边
        while(root != null){
            s.push(root);
            root = root.left;
        }
        TreeNode curr;
        TreeNode lastVisited = null;
        while(!s.empty()){
            curr = s.pop();   //弹出栈顶元素
            //一个根节点被访问的前提是:无右子树或右子树已被访问过  
            if(curr.right != null && curr.right != lastVisited){
                //结点再次入栈
                s.push(curr);
                //进入右子树,其右子树必不为空
                curr = curr.right;
                while(curr != null){
                    //再走到右子树的最左边
                    s.push(curr);
                    curr = curr.left;
                }
            }else{
                //访问当前结点,更新上一次被访问的结点
                result.add(curr.val);
                lastVisited = curr;
            }
        }
        return result;
    }
}