LeetCode:求二叉树最大的高度

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.
Note:A leaf is a node with no children.

Example 1:
Input:[3,9,20,null,null,15,7]
Output:3

解题思路:
利用递归遍历即可,从根节点的左孩子的高度和根节点右孩子的高度,取出两者的最大值再加1便可以得到树的高度.
迭代法也可以做
#include <iostream>
#include <algorithm>
#include <queue>

using namespace std;

struct treenode{

    treenode* left;
    treenode* right;
    treenode(const int& _val):val(_val),left(nullptr),right(nullptr){}
private:
    const int val;
};

class Solution{
public:
    int maxdepthoftree(treenode* root){
        if(root==nullptr)
            return 0;
        return max(maxdepthoftree(root->left),maxdepthoftree(root->right))+1;
    }
    int maxoftree(treenode* root){
        if(root==nullptr)
            return 0;
        auto depth=0;
        queue<treenode*> node{{root}};
        while(!node.empty()){
            depth++;
            for(auto i=node.size();i>0;i--){
                treenode* q=node.front();
                node.pop();
                if(q->left)
                   node.push(q->left);
                if(q->right)
                   node.push(q->right);
            }
        }
    }
};

int main(int argc ,char* argv[]){
    treenode root(3);
    treenode node1(9),node2(20),node3(15),node4(7);
    root.left=&node1;
    root.right=&node2;
    node2.left=&node3;
    node2.right=&node4;
    cout<<Solution().maxdepthoftree(&root)<<endl;
    cout<<Solution().maxdepthoftree(&root)<<endl;
    return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

路上的追梦人

您的鼓励就是我最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值