关于二叉树以及利用二叉树将递归转化为非递归

完全二叉树的性质:
  1.每层的节点(第i层)2的i减1次方.
  2.深度为k的二叉树最多有2的k次方减1.
  3.叶子节点的总数等于度为2的节点数加1.
  4.n个节点的二叉树的深度为2的对数加1.
  5.(若为数组型的连续二叉树)左孩子序号为父节点的2倍加1,有孩子为2倍加2.
  6.最后一个父节点为总结点数除以2再减一。
  7.若总结点数为奇数,最后一个父节点才有右孩子。
 
   
           二叉树的插入算法:


public class BinaryTree {
 
 int data;      //根节点数据
 BinaryTree left;    //左子树
 BinaryTree right;   //右子树
 
 public BinaryTree(int data)    //实例化二叉树类
 {
  this.data = data;
  left = null;
  right = null;
 }
 
 public void insert(BinaryTree root,int data){     //向二叉树中插入子节点
  if(data>root.data)                               //二叉树的左节点都比根节点小
  {
   if(root.right==null){
    root.right = new BinaryTree(data);
   }else{
    this.insert(root.right, data); //若根有右节点,则递归把当前右节点当作跟继续下去,
   }
  }else{                                          //二叉树的右节点都比根节点大
   if(root.left==null){
    root.left = new BinaryTree(data);
   }else{
    this.insert(root.left, data);
   }
  }
 }
}


          二叉树非递归遍历:(利用栈,模拟栈的方式)
1.先序排列:(1.先将根节点入栈。2.将根节点出栈,分别将其右节点和左节点先后入栈。3.将栈顶出栈再循环2步骤)
public void preorderNoRecursion() {  
        System.out.print("binaryTree非递归先序遍历:");  
        LinkedList<Node<Integer>> stack = new LinkedList<Node<Integer>>(); //linkedlist中有ddFirst(),removeFirst(),addLast()等方法,所以可以当作栈来使用 
        stack.push(root);  
        Node<Integer> current = null;  
        while (!stack.isEmpty()) {  
            current = stack.pop();  
            System.out.print(current.getValue());  
            if (current.getRightChild() != null)  
                stack.push(current.getRightChild());  
            if (current.getLeftChild() != null)  
                stack.push(current.getLeftChild());  
        }  
        System.out.println();  
    } 
2.中序排列:(1.从根节点开始先将所有左节点依次入栈。2.若栈不为空,栈顶出栈,取其右节点。3.若存在入栈再取其左节点入栈直至左节点被取完,循环2步骤,若不存在循环2步骤)
public void inorderNoRecursion() {  
        System.out.print("binaryTree非递归中序遍历:");  
        LinkedList<Node<Integer>> stack = new LinkedList<Node<Integer>>();  
        Node<Integer> current = root;  
        while (current != null || !stack.isEmpty()) {  
            while(current != null) {  
                stack.push(current);  
                current = current.getLeftChild();  
            }  
            if (!stack.isEmpty()) {  
                current = stack.pop();  
                System.out.print(current.getValue());  
                current = current.getRightChild();  
            }  
        }  
        System.out.println();  
    }


   
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值