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;
    };
  • 相关阅读:
    (DP)codeforces
    (树状数组)POJ
    (树状数组)POJ
    (二维树状数组)POJ
    (模拟)HDU
    (暴力+深搜)POJ
    (判连通+暴力)UVA
    (深搜)UVA
    (暴力+各种算法)hihoCoder
    (尺取法)HDU
  • 原文地址:https://www.cnblogs.com/csudanli/p/5842911.html
Copyright © 2011-2022 走看看