代码随想录算法训练营第十六天|104.二叉树的最大深度 111.二叉树的最小深度 222.完全二叉树的节点个数

目录

LeeCode 104.二叉树的最大深度

LeeCode 111.二叉树的最小深度

LeeCode 222.完全二叉树的节点个数

基础思路

进阶思路


LeeCode 104.二叉树的最大深度

104. 二叉树的最大深度 - 力扣(LeetCode)

思路:使用后序遍历求根结点的高度,根结点的高度就是二叉树的最大深度。

class Solution {
public:
    int maxDepth(TreeNode* root) {
    	return getdepth(root); 
    }
    int getdepth(TreeNode* node) {
    	if (node == NULL) return 0;
    	int leftdepth = getdepth(node->left);
    	int rightdepth = getdepth(node->right);
    	return 1 + max(leftdepth,rightdepth);
	}
};

LeeCode 111.二叉树的最小深度

111. 二叉树的最小深度 - 力扣(LeetCode)

思路: 最小深度是根结点到最近的叶子结点的最短路径上的结点数量,通过后序遍历,将深度向上传,且每次都取较小值。另外,排除左子树/右子树为空的情况,即为答案。

class Solution {
public:
    int minDepth(TreeNode* root) {
        return getdepth(root);
    }
    int getdepth(TreeNode* node) {
    	if (node == NULL)  return 0;
    	int leftdepth = getdepth(node->left);
    	int rightdepth = getdepth(node->right);
    	if (node->left == NULL && node->right != NULL){
    		return 1 + rightdepth;
		}
		if (node->left != NULL && node->right == NULL){
    		return 1 + leftdepth;
		}
		int result = 1 + min(leftdepth,rightdepth);
		return result;
	}
};

LeeCode 222.完全二叉树的节点个数

222. 完全二叉树的节点个数 - 力扣(LeetCode)

基础思路:

像普通二叉树一样遍历整棵树,求出节点个数。

class Solution {
private:
    int getNodesNum(TreeNode* cur) {
        if (cur == NULL) return 0;
        int leftNum = getNodesNum(cur->left);      
        int rightNum = getNodesNum(cur->right);   
        int treeNum = leftNum + rightNum + 1;      
        return treeNum;
    }
public:
    int countNodes(TreeNode* root) {
        return getNodesNum(root);
    }
};

时间复杂度:O(n)        空间复杂度:O(log n) 

进阶思路:

利用满二叉树节点个数 = 2^(高度) - 1 的性质,若当前节点的左右子树为满二叉树,求出高度后用公式计算节点数。

判断是否为满二叉树:在完全二叉树中,递归向左遍历的深度等于递归向右遍历的深度。

class Solution {
public:
    int countNodes(TreeNode* root) {
    	if(root == NULL) return 0;
    	TreeNode* left = root->left;
    	TreeNode* right = root->right;
    	int ldepth = 0, rdepth = 0;
    	while (left) {
    		left = left->left;
    		ldepth ++;
		}
		while (right) {
			right = right->right;
			rdepth ++;
		}
		if  (ldepth == rdepth) {
			return (2 << ldepth) - 1;
		}
		return countNodes(root->left) + countNodes(root->right) + 1;
    }
};

时间复杂度:O(log n x log n)          空间复杂度:O(log n)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值