zoukankan      html  css  js  c++  java
  • 二叉树前中后递归遍历

    1 public class Node {
    2     public int value;
    3     public Node left;
    4     public Node right;
    5 
    6     public Node (int data){
    7         this.value = data;
    8     }
    9 }
     1 public class BinaryTreeMethod {
     2 
     3     /**
     4      * 二叉树递归前序遍历
     5      * @param head
     6      */
     7     public void preOrderRecur(Node head){
     8         if(head == null){
     9             return;
    10         }
    11         System.out.print(head.value + " ");
    12         preOrderRecur(head.left);
    13         preOrderRecur(head.right);
    14     }
    15 
    16     /**
    17      * 二叉树递归中序遍历
    18      * @param head
    19      */
    20     public void inOrderRecur(Node head){
    21         if(head == null){
    22             return;
    23         }
    24         inOrderRecur(head.left);
    25         System.out.print(head.value + " ");
    26         inOrderRecur(head.right);
    27     }
    28 
    29     /**
    30      * 二叉树递归后序遍历
    31      * @param head
    32      */
    33     public void postOrderRecur(Node head){
    34         if(head == null){
    35             return;
    36         }
    37         postOrderRecur(head.left);
    38         postOrderRecur(head.right);
    39         System.out.print(head.value + " ");
    40     }
    41 }

    测试代码:

     1 public class Test {
     2 
     3     public  static void  main(String[] args){
     4         Node head = new Node(3);
     5         Node left = new Node(5);
     6         Node right = new Node(2);
     7         head.left = left;
     8         head.right = right;
     9 
    10         left.left = new Node(1);
    11         right.left = new Node(7);
    12 
    13         BinaryTreeMethod method = new BinaryTreeMethod();
    14         method.preOrderRecur(head);
    15         System.out.println();
    16         method.inOrderRecur(head);
    17         System.out.println();
    18         method.postOrderRecur(head);
    19     }
    20 }
  • 相关阅读:
    TLE: poj 1011 Sticks
    UVa 116 Unidirectional TSP
    csuoj 1215 稳定排序
    UVa 103 Stacking Boxes
    UVa 147 Dollars
    UVa 111 History Grading
    怎么在ASP.NET 2.0中使用Membership
    asp.net中如何删除cookie?
    ASP.NET中的HTTP模块和处理程序[收藏]
    NET开发中的一些小技巧
  • 原文地址:https://www.cnblogs.com/huangyichun/p/6010276.html
Copyright © 2011-2022 走看看