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.       
  • 相关阅读:
    接口中解决默认方法冲突
    继承中的访问域问题
    继承中的多态问题
    Java中方法的调用过程
    【JS】表格获取每一列方法
    【Git报错】 ! [rejected] master -> master (fetch first)
    【Vue】vue-cli配置proxyTable调用服务器接口
    layui监听多个radio事件
    【总结】display属性inline,block,inline-block
    【实例总结】fixed定位元素内部滚动显示
  • 原文地址:https://www.cnblogs.com/kisty/p/4918124.html
Copyright © 2011-2022 走看看