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.       
  • 相关阅读:
    Manjaro 更新vim插件或者系统后 YCM失效
    UVA 10635 Prince and Princess
    HDU 4489 The King's Ups and Downs
    HDU 1542 矩形面积并
    POJ 2528 Mayor's poster
    读 CSI讲义 费马小定理
    JavaWeb——Servlet开发2
    JavaWeb——Servlet开发1
    LeetCode——264. Ugly Number II
    LeetCode——540. Single Element in a Sorted Array
  • 原文地址:https://www.cnblogs.com/kisty/p/4918124.html
Copyright © 2011-2022 走看看