zoukankan      html  css  js  c++  java
  • leetcode 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 depth=0,high=0;
            dfs(root,depth,high);
            return depth;
        }
        void dfs(TreeNode* root,int &depth,int high){
            if(root==NULL) return;
            high++;
            if(high>depth) depth=high;
            dfs(root->left,depth,high);
            dfs(root->right,depth,high);
            high--;
        }
    };

    精简版:

    /**
     * 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) {
            return root==NULL? 0: 1+max(maxDepth(root->left),maxDepth(root->right));
        }
    };
  • 相关阅读:
    Live2D 看板娘
    Live2D 看板娘
    Live2D 看板娘
    Live2D 看板娘
    Live2D 看板娘
    Live2D 看板娘
    Live2D 看板娘
    Live2D 看板娘
    Live2D 看板娘
    [转载]MySQL5.5 配置文件 my.ini 1067错误
  • 原文地址:https://www.cnblogs.com/joelwang/p/10692423.html
Copyright © 2011-2022 走看看