力扣144,145,94二叉树前、中、后序遍历迭代法统一模板JAVA

力扣144,145,94二叉树前、中、后序遍历迭代法统一模板JAVA,第1张

力扣144,145,94二叉树前、中、后序遍历迭代法统一模板JAVA
public List preorderTraversal(TreeNode root) {//前序
        List result = new ArrayList<>();
        Stack tmp = new Stack<>();
        if(root != null) tmp.push(root);
        TreeNode cur = null;
        while(!tmp.isEmpty()){
            cur = tmp.pop();
            if(cur!=null){
                if(cur.right!=null) tmp.push(cur.right);
                if(cur.left!=null) tmp.push(cur.left);
                tmp.push(cur);
                tmp.push(null); // 中节点访问过,但是还没有处理,加入空节点做为标记。
            } else{// 只有遇到空节点的时候,才将下一个节点放进结果集
                cur = tmp.pop();// 重新取出栈中元素
                result.add(cur.val);
            }
        }
        return result;
    }
public List preorderTraversal(TreeNode root) { //中序
        List result = new ArrayList<>();
        Stack tmp = new Stack<>();
        if(root != null) tmp.push(root);
        TreeNode cur = null;
        while(!tmp.isEmpty()){
            cur = tmp.pop();
            if(cur!=null){
                if(cur.right!=null) tmp.push(cur.right);
                tmp.push(cur);
                tmp.push(null);
                if(cur.left!=null) tmp.push(cur.left);
            }
            else{
                cur = tmp.pop();
                result.add(cur.val);
            }
        }
        return result;
    }

public List preorderTraversal(TreeNode root) { //后序
        List result = new ArrayList<>();
        Stack tmp = new Stack<>();
        if(root != null) tmp.push(root);
        TreeNode cur = null;
        while(!tmp.isEmpty()){
            cur = tmp.pop();
            if(cur!=null){
                tmp.push(cur);
                tmp.push(null);
                if(cur.right!=null) tmp.push(cur.right);
                if(cur.left!=null) tmp.push(cur.left);
            }
            else{
                cur = tmp.pop();
                result.add(cur.val);
            }
        }
        return result;
    }

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/4657830.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-06
下一篇 2022-11-06

发表评论

登录后才能评论

评论列表(0条)

保存