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));
        }
    };
  • 相关阅读:
    R
    R 包的安装,使用,更新
    R 安装 简单实用
    R 介绍
    mongo:用户管理
    MySQL 书籍
    mongo: 索引
    blog
    游标处理
    如何在ASP.NET的web.config配置文件中添加MIME类型
  • 原文地址:https://www.cnblogs.com/joelwang/p/10692423.html
Copyright © 2011-2022 走看看