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

    给定一个二叉树,找出其最大深度。

    二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。

    说明: 叶子节点是指没有子节点的节点。

    示例:
    给定二叉树 [3,9,20,null,null,15,7],

    3
    /
    9 20
    /
    15 7
    返回它的最大深度 3 。

    /**
     * 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) {
            if(!root)
                return 0;
            
            int leftDepth=maxDepth(root->left);
            int rightDepth=maxDepth(root->right);
            return max(leftDepth,rightDepth)+1;
        }
    };

     BFS

    /**
     * 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) {
            if(!root)
                return 0;
            
            queue<TreeNode*> q;
            q.push(root);
            int depth=0;
            while(!q.empty())
            {
                ++depth;
                int layer=q.size();
                while(layer>0)//按层处理,把每层的结点处理完
                {
                    auto tmp=q.front();
                    q.pop();
                    if(tmp->left)
                        q.push(tmp->left);
                    if(tmp->right)
                        q.push(tmp->right);
                    --layer;
                }
            }
            return depth;
        }
    };
  • 相关阅读:
    标准C语言(9)
    标准C语言(8)
    标准C语言(7)
    标准C语言(6)
    标准C语言(5)
    标准C语言(4)
    标准C语言(3)
    标准C语言(1)
    Linux基础
    Kafka 学习笔记之 Kafka0.11之console-producer/console-consumer
  • 原文地址:https://www.cnblogs.com/tianzeng/p/11767278.html
Copyright © 2011-2022 走看看