二叉树的简易遍历

本文介绍了二叉树的三种遍历方式:前序遍历(根左右)、中序遍历(左根右)、后序遍历(左右根),并提供了计算二叉树节点个数和叶子个数的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

二叉树定义不多说了
用链表实现二叉树

首先,定义一个类


class Node{
    char value;
    Node left;
    Node right;
    public Node(char value){
        this.value = value;
        left = right = null;
    }
}

Node 也可以叫二叉链

遍历的方法有三种:

  1. 前序遍历
    根左右
  2. 中序遍历
    左根右
  3. 后序遍历
    左右根

注意左和右是指左子树和右子树

前序遍历

public void preOrder(Node root){
        //终止条件: 空树
        if(root == null){
            return;
        }
        else{
            //递推
            //根
            System.out.print(root.value);
            //左子树
            preOrder(root.left);
            //右子树
            preOrder(root.right);
        }
    }

中序遍历

    public  void inOrder(Node root){
        if(root != null){
            //访问左子树
            inOrder(root.left);
            //根
            System.out.print(root.value);
            //访问右子树
            inOrder(root.right);
        }
    }
在这里插入代码片

后序遍历

    public void postOrfer(Node root){
        if(root != null){
            //左子树
            postOrfer(root.left);
            //右子树
            postOrfer(root.right);
            //根
            System.out.print(root.value);
        }
    }

当前树的结点个数

    public void getSize1(Node root){
        if(root != null){
            //左子树
            getSize1(root.left);
            //右子树
            getSize1(root.right);
            //根
            ++size;
        }
    }
    public int getSize2(Node root){
        if(root == null)
            return 0;
        if(root.left == null && root.right == null)
            return 1;
        //整棵树节点: 当前节点 + 左右子树节点的个数
        return getSize2(root.left) + getSize2(root.right) + 1;
    }

思路:当前节点加左右子树的结点个数

求这颗树的叶子个数

    public int getLeafSize2(Node root){
        if(root == null)
            return 0;
        if(root.left == null && root.right == null)
            return 1;
        return getLeafSize2(root.left) + getLeafSize2(root.right);
    }

    public int getKSize(Node root, int k){
        if(root == null)
            return 0;
        if(k == 1)
            return 1;
        return getKSize(root.left, k - 1) + getKSize(root.right, k - 1);
    }

思路:左右树的叶子个数和

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值