二叉树的遍历--深度优先遍历

深度优先遍历包括:前中后序遍历

比较容易实现的是利用递归迭代进行遍历操作

前序遍历

public static void preOrderTree(Node root){
       if(root==null){
           return;
       }
        System.out.print(" "+root.val);
       preOrderTree(root.left);
       preOrderTree(root.right);
       //时间复杂度为O(n)

中序遍历

    public static void inOrderTree(Node root){
        if(root==null){
            return;
        }
        inOrderTree(root.left);
        System.out.print(" "+root.val);
        inOrderTree(root.right);

    }

后序遍历

 public static void postOrderTree(Node root){
        if(root==null){
            return;
        }
        postOrderTree(root.left);
        postOrderTree(root.right);
        System.out.print(" "+root.val);
      }

关于二叉树的深度优先遍历的一些常见应用

//计算二叉树中节点的个数 
     public static int calcTreeNode(Node root){
         if(root==null){
           return 0;
       }
          count++;
          calcTreeNode(root.left);
          calcTreeNode(root.right);
          return count;
       }
      public static int calcTreeNode_1(Node root){
          if(root==null){ 
              return 0;
          }
          int left=calcTreeNode_1(root.left);
          int right=calcTreeNode_1(root.right);
          return left+right;
      }
//求二叉树的叶子结点个数
      public static void cacLeafNode(Node root){
          if(root==null){
              return;
          }
          //代表结点 用来判断是否为叶子节点
          if(root.left==null && root.right==null){
              count++;
          }
          cacLeafNode(root.left);
          cacLeafNode(root.right);
    }
//求二叉树的高度
       public static int calcHigh(Node root){
          if(root==null){
              return 0;
          }
          int left=calcHigh(root.left);
          int right=calcHigh(root.right);
          int height=Math.max(left,right);
          return height+1;
}
//计算第k层的结点个数
       public static int calcKlevel(Node root,int k){
          if(root==null){
              return 0;
          }
          if(k==1){
              return 1;
          }
          int left=calcKlevel(root.left,k-1);
          int right=calcKlevel(root.right,k-1);
          int count=left+right;
          return count;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值