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语言I博客作业04
    C语言I博客作业03
    C语言I博客作业02
    作业01
    第八周作业
  • 原文地址:https://www.cnblogs.com/tianzeng/p/11767278.html
Copyright © 2011-2022 走看看