微软面试100题系列---二叉树的遍历递归和非递归实现

本文详细介绍了二叉树的前序、中序和后序遍历算法,并提供了递归和非递归两种实现方式的具体代码示例。

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

题目

用递归和非递归两种方法实现二叉树的遍历

实现

前序遍历

递归实现

void preorderRecursive(Node root
{
    if(node==null){
       return;
    }
    visit(root);
    preorderRecursive(root.left);
    preorderRecursive(root.right);
}

非递归实现

借助一个栈实现

void preorderNonrecursive(Node root){
   Stack stack=new Stack();
   stack.push(root);
   while(!stack.isEmpty()){
       Node node=stack.pop();
       visit(node);
       if(node.left!=null)
           stack.push(node.left);
       if(node.right!=null)
           stack.push(node.right);
   }
}

中序遍历

递归

void inorderRecursive(Node root
{
    if(node==null){
       return;
    }
    inorderRecursive(root.left);
    visit(root);
    inorderRecursive(root.right);
}

非递归

void inorderNonrecursive(Node root){
   Stack s=new Stack();
   Node current=root;
   while(!s.isEmpty() || current!=null){
      if(current!=null) 
       {
          s.push(current);
          current=current.left;
       }else{
          current=s.pop();
          visit(current);
          current=current.right;
       }
}

后序遍历

非递归实现

void postorderNonrecursive(Node root){
    Stack s1=new Stack();
    Stack s2=new Stack();
    s1.push(root);
    while(!s1.isEmpty()){
       Node node=s1.pop();
       s2.push(node);
       if(node.left!=null)
           s1.push(node.left);
       if(node.right!=null)
           s1.push(node.right);
    }
    while(!s2.isEmpty()){
       visit(s2.pop());
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值