获取二叉树性质相关

树的结构为

public class TreeNode {
    public int val;
    public TreeNode left;
    public TreeNode right;
    public TreeNode(int x) 
    { 
        val = x; 
    }
}

二叉树中叶子节点的个数

叶子指没有两个孩子的节点。递归的方法是,一个节点下的叶子节点数目等于其左子树和右子树叶子节点数目之和

public int leavesNum(TreeNode root) {
    if(root == null) return 0;
    else if(root.left == null && root.right == null) return 1;
    else return leavesNum(root.left)+leavesNum(root.right);
}

二叉树第K层节点数目

从根结点向下第k层的节点数,应该等于根左右孩子向下k-1层的节点数之和。递归不断向下。

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

二叉树最大高度

https://leetcode.com/problems/maximum-depth-of-binary-tree/
Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

最大高度就是指树的高度:树的高度应该为其左子树和右子树的最大高度+1

public int maxDepth(TreeNode root) {
    if(root == null) return 0;
    else{
        int leftmax = maxDepth(root.left), rightmax = maxDepth(root.right);
        return leftmax > rightmax ? (leftmax+1) : (rightmax+1);
    }
}

二叉树最小高度

https://leetcode.com/problems/minimum-depth-of-binary-tree/
Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node

二叉树最小高度并不仅仅是上一道题的相反逻辑,注意,最大高度直接递归可以保证是从根到叶子节点,但是最小高度用这种逻辑递归并不能保证是到叶子节点(可能会是从根到某个只有一个孩子的节点)

public int minDepth(TreeNode root) {
    if(root == null) return 0;
    else{
        int leftmin = minDepth(root.left), rightmin = minDepth(root.right);
        if(leftmin == 0) return rightmin+1;
        if(rightmin == 0) return leftmin+1;
        else return leftmin < rightmin ? leftmin+1 : rightmin+1;
    }   
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值