zoukankan      html  css  js  c++  java
  • LeetCode 104. 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.

    这是个很简单的题目,只需对树进行深度遍历即可,如果某个节点的深度大于最大深度,则将最大深度的值改为这个深度

    遍历结束后,这个最大深度即为所求值

    /**
     * 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:
        void depthFirstSearch(TreeNode* root,int len)
        {
            if (!root)return;
            depthFirstSearch(root->left, len + 1);
            depthFirstSearch(root->right, len + 1);
            if (maxD < len+1)maxD = len+1;
        }
        int maxDepth(TreeNode* root) {
            depthFirstSearch(root, 0);
            return maxD;
        }
    private:
        size_t maxD=0;
    };
  • 相关阅读:
    python---模块与包
    python---迭代器与生成器
    python---装饰器
    Python---函数
    Python---文件操作
    Python---数据类型
    浅谈UBUNTU
    java 键盘输入多种方法
    动态规划解最长公共子序列问题
    线段树
  • 原文地址:https://www.cnblogs.com/csudanli/p/5842911.html
Copyright © 2011-2022 走看看