zoukankan      html  css  js  c++  java
  • 【数据结构基础复习】二叉树的递归遍历(一)

    一、绪论

      今天来点简单的,好久没有写过代码了,基础知识都快忘了,从今天开始还是得简简单单的写一些,作为复习吧,不能光搞研究,代码给拉下了。

    二、目的

      复习二叉树的遍历

      二叉树的遍历有三种,前中后。这里的前中后是根据树的根节点来看的,前序就是,根节点---左子节点---右子节点。其余类同。其实递归遍历没什么好谢的,都是教材上有的,这里直接把代码贴出来,不做过多的累述。

    //前序遍历;
        public void preOderRecur( Node root ){
            if(root == null){
                return ;
            }
    
            System.out.print(root.value + " ");
            preOderRecur(root.left);
            preOderRecur(root.right);
        }
    
        //中序遍历;
        public void inOderRecur( Node root ){
            if(root == null){
                return ;
            }
    
            inOderRecur(root.left);
            System.out.print(root.value + " ");
            inOderRecur(root.right);
        }
    
        //后序遍历;
        public void posOderRecur( Node root ){
            if(root == null){
                return ;
            }
    
            posOderRecur(root.left);
            posOderRecur(root.right);
            System.out.print(root.value + " ");
        }

      当然在遍历二叉树的时候,还得构造二叉树,这里同样是采用递归的方式去构造。

     1 //构造二叉树;
     2     public Node root ;
     3     protected Node creBinaryTree(int[] seeds){
     4         root = null ;
     5         for(int node : seeds){
     6             root = insert(node) ;
     7         }
     8         return root ;
     9     }
    10     public Node insert(int data){
    11         return root =  insert(root , data);
    12     }
    13     public Node insert(Node node ,int value){
    14         if(node == null){
    15             node = new Node(value) ;
    16         } else {
    17             if(node.left== null) {
    18                 node.left = insert(node.left, value);
    19             } else {
    20                 node.right = insert(node.right, value);
    21             }
    22         }
    23         return node;
    24     }
  • 相关阅读:
    快速入门 ASP.NET MVC
    关于ASP.NET中由于无法创建应用程序域,因此未能执行请求解决方案
    Microsoft ASP.NET MVC Beta IIS6 部署
    弹窗显示正在执行的任务
    多线程加深理解_进攻五个城
    反射与配置文件简单使用
    C#中MemberwiseClone的理解
    C# App.config 自定义 配置节 报错“配置系统未能初始化” 解决方法
    多线程信号源的理解
    日志的记录
  • 原文地址:https://www.cnblogs.com/panghaohan/p/6526711.html
Copyright © 2011-2022 走看看