zoukankan      html  css  js  c++  java
  • java 二叉树递归遍历算法

    1.  //递归中序遍历  
    2.     public void inorder() {  
    3.         System.out.print("binaryTree递归中序遍历:");  
    4.         inorderTraverseRecursion(root);  
    5.         System.out.println();  
    6.     }  
    7.       
    8.     //层次遍历  
    9.     public void layerorder() {  
    10.         System.out.print("binaryTree层次遍历:");  
    11.         LinkedList<Node<Integer>> queue = new LinkedList<Node<Integer>>();  
    12.         queue.addLast(root);  
    13.         Node<Integer> current = null;  
    14.         while(!queue.isEmpty()) {  
    15.             current = queue.removeFirst();  
    16.             if (current.getLeftChild() != null)  
    17.                 queue.addLast(current.getLeftChild());  
    18.             if (current.getRightChild() != null)  
    19.                 queue.addLast(current.getRightChild());  
    20.             System.out.print(current.getValue());  
    21.         }  
    22.         System.out.println();  
    23.     }  
    24.   
    25.       
    26.     //获得二叉树深度     
    27.     public int getDepth() {  
    28.         return getDepthRecursion(root);  
    29.     }  
    30.       
    31.     private int getDepthRecursion(Node<Integer> node){  
    32.         if (node == null)  
    33.             return 0;  
    34.         int llen = getDepthRecursion(node.getLeftChild());  
    35.         int rlen = getDepthRecursion(node.getRightChild());  
    36.         int maxlen = Math.max(llen, rlen);  
    37.         return maxlen + 1;  
    38.     }  
    39.     //递归先序遍历      
    40.     public void preorder() {  
    41.         System.out.print("binaryTree递归先序遍历:");  
    42.         preorderTraverseRecursion(root);  
    43.         System.out.println();  
    44.     }  
    45.       
    46.       
  • 相关阅读:
    Dom解析
    几道算法水题
    Bom和Dom编程以及js中prototype的详解
    sqlserver练习
    java框架BeanUtils及路径问题练习
    Java的IO以及线程练习
    在数据库查询时解决大量in 关键字的方法
    SaltStack--配置管理
    SaltStack--远程执行
    SaltStack--快速入门
  • 原文地址:https://www.cnblogs.com/kisty/p/4918124.html
Copyright © 2011-2022 走看看