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     }
  • 相关阅读:
    CF Gym 101955G Best ACMer Solves the Hardest Problem 平面加点,删点,点加权(暴力)
    CF Gym 101955C Insertion Sort
    狩猎大赛(社团周赛)
    CF 1215 D Ticket Game (博弈)
    CF1215 C Swap Letters(思维题)
    CF 1215 B The Number of Products(思维题)
    HDU 6740 MUV LUV EXTRA(求循环节)
    BZOJ 1491 [NOI2007]社交网络(Floyd变形)
    BZOJ 3039 玉蟾宫
    【luogu4124】【bzoj4521】 [CQOI2016]手机号码 [数位dp]
  • 原文地址:https://www.cnblogs.com/panghaohan/p/6526711.html
Copyright © 2011-2022 走看看