zoukankan      html  css  js  c++  java
  • 104. 二叉树的最大深度

    题目

    104. 二叉树的最大深度

    我的思路

    深搜递归,广搜队列

    我的实现

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        int maxDepth(TreeNode* root) {
            //广搜三件套:初始化队列,加一个队头,遍历队列
            //队列元素:节点+当前层数     
            int maxDepth=0;
            queue<pair<TreeNode*,int>> q;
            if(root!=NULL)
            q.push(make_pair(root,1));
            while(!q.empty()){
                pair temp = q.front();
                q.pop();
                maxDepth = max(maxDepth,temp.second);
                if(temp.first->left!=NULL) q.push(make_pair(temp.first->left,temp.second+1));
                if(temp.first->right!=NULL) q.push(make_pair(temp.first->right,temp.second+1));
            }
            return maxDepth;
        }
    };
    //深搜or广搜
    /*深搜
    class Solution {
    public:
        int search(TreeNode *root){
            if(root==NULL)return 0;
            int length = 1;
            if (root->left!=NULL){
                length = search(root->left)+1;
            }
            if(root->right!=NULL){
                length = max(length,search(root->right)+1);
            }
            return length;
        }
        int maxDepth(TreeNode* root) {
            return search(root);
        }
    };
    */
    /*广搜
    class Solution {
    public:
        int maxDepth(TreeNode* root) {
            //广搜三件套:初始化队列,加一个队头,遍历队列
            //队列元素:节点+当前层数     
            int maxDepth=0;
            queue<pair<TreeNode*,int>> q;
            if(root!=NULL)
            q.push(make_pair(root,1));
            while(!q.empty()){
                pair temp = q.front();
                q.pop();
                maxDepth = max(maxDepth,temp.second);
                if(temp.first->left!=NULL) q.push(make_pair(temp.first->left,temp.second+1));
                if(temp.first->right!=NULL) q.push(make_pair(temp.first->right,temp.second+1));
            }
            return maxDepth;
        }
    };
    */

    深搜广搜时间复杂度都是n,n为节点数。空间复杂度都是logn,层数。

    拓展学习

    更简洁的深搜写法

    class Solution {
    public:
        int maxDepth(TreeNode* root) {
            if (root == nullptr) return 0;
            return max(maxDepth(root->left), maxDepth(root->right)) + 1;
        }
    };
    
    作者:LeetCode-Solution
    链接:https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/solution/er-cha-shu-de-zui-da-shen-du-by-leetcode-solution/
    来源:力扣(LeetCode)
    著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
  • 相关阅读:
    LL(1)文法的判断,递归下降分析程序
    消除左递归
    DFA最小化,语法分析初步
    非确定的自动机NFA确定化为DFA
    正规式、正规文法与自动机
    第03组 Alpha事后诸葛亮
    第03组 Alpha冲刺(4/4)
    第03组 Alpha冲刺(3/4)
    第03组 Alpha冲刺(2/4)
    第03组 Alpha冲刺(1/4)
  • 原文地址:https://www.cnblogs.com/BoysCryToo/p/13392465.html
Copyright © 2011-2022 走看看