<leetcode> Inorder, Preorder Traversal

本文详细介绍了非递归的二叉树遍历算法,包括中序遍历和前序遍历的过程及实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

非递归的binary tree traversal:

Inorder:

从根开始,首先沿着左边遍历,并把每个左节点添加到栈。当遍历到null时,从栈中释放一个节点,并访问节点。然后遍历该节点的右边, 直到栈中没有节点


/*;
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        ArrayList<Integer> list=new ArrayList<Integer>();
        Stack<TreeNode> s=new Stack<TreeNode>();
        TreeNode subroot=root;
        TreeNode current=root;
        while(!s.isEmpty()||current!=null){
            while(current!=null){
                s.push(current);
                current=current.left;
            }
            current=s.pop();
            list.add(current.val);
            current=current.right;
        }
        return list;
    }
}


preorder:

从根开始,首先沿着左边遍历,并把每个左节点添加到栈,不同的是当添加的时候访问该节点,这样父节点就在子结点之前访问。后面和inorder类似,遇到null的时候,从栈中释放,遍历其右子树。


/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        Stack<TreeNode> s=new Stack<TreeNode>();
        ArrayList<Integer> list=new ArrayList<Integer>();
        /*TreeNode current=root;
        TreeNode subroot=root;
        while(subroot!=null){
            current=subroot;
            while(current!=null){
                list.add(current.val);
                if(current.right!=null){
                    s.push(current.right);
                }
                current=current.left;
            }
            if(s.isEmpty()){
                subroot=null;
            }
            else subroot=s.pop();
        }*/
        TreeNode current=root;
        while(!s.isEmpty()||current!=null){
            while(current!=null){
                s.push(current);
                list.add(current.val);
                current=current.left;
            }
            current=s.pop();
            current=current.right;
        }
        return list;
    }
    
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值