二叉树_基础操作

1.二叉树前中后序遍历(递归)

核心思想:递归处理

  1. 前序:根左右
  2. 中序:左根右
  3. 后序:左右根
class Node {
    public char val;
    public Node left;
    public Node right;

    public Node(char val) {
        this.val = val;
    }
}

public class TestTree {
    // 先序
    public static void preOrder(Node root) {
        if (root == null) {
            return;
        }
        System.out.print(root.val + " ");
        preOrder(root.left);
        preOrder(root.right);
    }
    
    // 中序
    public static void inOrder(Node root) {
        if (root == null) {
            return;
        }
        inOrder(root.left);
        System.out.print(root.val + " ");
        inOrder(root.right);
    }

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

2.二叉树层次遍历

链接:层次遍历及相关问题

3.计算所有节点个数

核心思想:整个树节点个数 = 根结点的个数(1) + 左子树节点个数(递归) + 右子树节点个数(递归)

// 计算节点个数
    public static int size(Node root){
        if(root == null){
            return 0;
        }
        // 递归思想 “拆分问题”
        // 整个树节点个数 = 根结点的个数(1) + 左子树节点个数(递归) + 右子树节点个数(递归)
        return 1 + size(root.left) + size(root.right);
    }

4.计算叶子节点个数

核心思想:递归处理 叶子节点个数 = 左子树叶子节点个数 + 右子树叶子节点个数

// 计算叶子节点个数
    public static int leafSise(Node root){
        if(root == null){
            return 0;
        }

        if(root.left==null && root.right==null){
            return 1; // 叶子节点
        }
        
        // 叶子节点个数 = 左子树叶子节点个数 + 右子树叶子节点个数
        return leafSise(root.left)+leafSise(root.right);
    }

5.计算第K层节点个数

核心思想:递归处理 第 k 层节点个数 = 左子树的 k-1 层节点个数 + 右子树的 k-1 层节点个数
eg:

// 求第 K 层节点个数
    public static int kLevelSize(Node root, int k){
        if(k < 0 || root == null){
            return 0;
        }
        if(k == 1){
            return 1;
        }
        
        //第 k 层节点个数 = 左子树的 k-1 层节点个数 + 右子树的 k-1 层节点个数
        return kLevelSize(root.left,k-1) + kLevelSize(root.right,k-1);
    }

6.在二叉树中查找指定元素

// 在二叉树中查找指定元素
    // 存在返回该节点的引用  不存在返回 null
    Node find(Node root, char toFind){
        if(root == null){
            return null;
        }
        if(root.val == toFind){
            return root;
        }

        // 分别递归的去查找左右子树
        Node result = find(root.left,toFind);
        if(result != null){
            return result; 
        }
        find(root.left,toFind);
        return find(root.right,toFind);
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值