【LeetCode】Maximum Depth of Binary Tree

本文详细介绍了如何使用递归、循环(栈与队列)等方法来计算二叉树的最大深度,并提供了代码实现及功能测试案例。

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

参考:

题目描述

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就是根的最大高度


循环法——栈:麻烦一些,跟后序遍历的循环法相似,需要记录上一个被遍历的结点。
循环法目前只用后序的方法解决了,但 先序和中序暂时还没有解决。暂时没想到方法,如果有人知道欢迎讨论。



循环法——队列:这个是参考网上代码,这个思路确实不错,需要学习的是如果标记一层遍历结束。

总结

一个出错的地方。记录上一个结点的变量 preNode的初始值不应该是NULL,应该是root

代码示例


#include 
   
    
#include 
    
     
#include 
     
       
using namespace std;

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
struct TreeNode {
	int val;
	TreeNode *left;
	TreeNode *right;
	TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 };
#if 0//递归法 
class Solution {
public:
    int maxDepth(TreeNode *root) {
        if(root == NULL)
        	return 0;
       	int left = maxDepth(root->left);
       	int right = maxDepth(root->right);
       	if(left > right)
       		return left + 1;
  		else
  			return right + 1;        	
    }
};
#elif 0//循环法  栈 深度优先 
class Solution {
public:
    int maxDepth(TreeNode *root) {
        if(root == NULL)
        	return 0;
       	stack
      
        treeStk;
       	treeStk.push(root);
		int maxhigh = 1, tmphigh = 1;
		TreeNode *preNode = root;		//记录上一个被遍历的结点   初始值要是root 
		while(!treeStk.empty())
		{
			TreeNode *topNode = treeStk.top();
			//printf("top = %d high = %d\n",topNode->val,tmphigh);
			if(topNode->left == NULL && topNode->right == NULL/*叶子结点*/)
			{
				if(tmphigh > maxhigh)	maxhigh = tmphigh;
				treeStk.pop();
				preNode = topNode; 
				continue;				 
			}
			if(topNode->right == preNode || topNode->left == preNode)//孩子结点已经被遍历 
			{
				tmphigh--;
				treeStk.pop();
				preNode = topNode;
				continue;	
			}
			if(topNode->right != NULL) treeStk.push(topNode->right);
			if(topNode->left != NULL) treeStk.push(topNode->left);
			tmphigh++;//高度加1	
		}
		return maxhigh;
    }
};
#elif 1 //队列广度优先 
class Solution {
public:
    //二叉树最大深度(层次遍历,遍历一层高度加1)
    int maxDepth(TreeNode *root) {
        int height = 0,rowCount = 1;
        if(root == NULL){
            return 0;
        }
        //创建队列
        queue
       
         queue;
        //添加根节点
        queue.push(root);
        //层次遍历
        while(!queue.empty()){
            //队列头元素
            TreeNode *node = queue.front();
            //出队列
            queue.pop();
            //一层的元素个数减1,一层遍历完高度加1
            rowCount --;
            if(node->left){
                queue.push(node->left);
            }
            if(node->right){
                queue.push(node->right);
            }
            //一层遍历完
            if(rowCount == 0){
                //高度加1
                height++;
                //下一层元素个数
                rowCount = queue.size();
            }
        }
        return height;
    }
 
}; 
#endif 

/*功能测试*/
void test0()
{
/*
				1
		2				3
	4		5		6		7
*/ 
	TreeNode node1(1);
	TreeNode node2(2);
	TreeNode node3(3);
	TreeNode node4(4);
	TreeNode node5(5);
	TreeNode node6(6);
	TreeNode node7(7);
	node1.left = &node2;
	node1.right = &node3;
	
	node2.left = &node4;
	node2.right = &node5;
	
	node3.left = &node6;
	node3.right = &node7;
	
	Solution so;
	int high = so.maxDepth(&node1);
	

	if(high == 3)
		printf("---------------------passed\n");
	else
		printf("---------------------failed\n");	
}

/*功能测试*/
void test1()
{
/*
				1
		2	
	3	
*/ 
	TreeNode node1(1);
	TreeNode node2(2);
	TreeNode node3(3);
	
	node1.left = &node2;
	
	node2.left = &node3;
	
	Solution so;
	int high = so.maxDepth(&node1);
	

	if(high == 3)
		printf("---------------------passed\n");
	else
		printf("---------------------failed\n");	
}

/*功能测试*/
void test2()
{
/*
						1
			2					3
	4				5
				6
					7
*/ 
	TreeNode node1(1);
	TreeNode node2(2);
	TreeNode node3(3);
	TreeNode node4(4);
	TreeNode node5(5);
	TreeNode node6(6);
	TreeNode node7(7);
	node1.left = &node2;
	node1.right = &node3;
	
	node2.left = &node4;
	node2.right = &node5;
	
	node5.left = &node6;
	node6.right = &node7;
	
	Solution so;
	int high = so.maxDepth(&node1);
	

	if(high == 5)
		printf("---------------------passed\n");
	else
		printf("---------------------failed\n");	
}
/*功能测试*/
void test3()
{
	Solution so;
	int high = so.maxDepth(NULL);
	

	if(high == 0)
		printf("---------------------passed\n");
	else
		printf("---------------------failed\n");	
}
/*功能测试*/
void test4()
{
/*
						1
*/ 
	TreeNode node1(1);
	Solution so;
	int high = so.maxDepth(&node1);
	

	if(high == 1)
		printf("---------------------passed\n");
	else
		printf("---------------------failed\n");	
}
int main()
{
	test0();
	test1();
	test2();
	test3();
	test4();
	return 0;
}

       
      
     
    
   


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



推荐学习C++的资料

C++标准函数库
在线C++API查询

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值