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

    这道题非常直接,只需要递归深搜就可以。需要注意的是递归的终止条件:root为空,深度为0;root没有孩子,深度为1。如果存在孩子,则递归深搜下去。

    /**
     * Definition for binary tree
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        int maxDepth(TreeNode *root) {
            // IMPORTANT: Please reset any member data you declared, as
            // the same Solution instance will be reused for each test case.
            if(root == NULL)
                return 0;
            
            if(root -> left == NULL && root -> right == NULL)
                return 1;
            
            int leftDepth = 0, rightDepth = 0;
            if(root -> left != NULL)
                leftDepth = maxDepth(root -> left) + 1;
            if(root -> right != NULL)
                rightDepth = maxDepth(root -> right) + 1;
            
            return (leftDepth > rightDepth) ? leftDepth : rightDepth;
            
        }
        
    };

    写完后看了博客园另一位博主的写法,发现自己的第一个if其实只是为了填补后面写的代码的漏洞,这个问题完全可以用精简得多的方式写出来。/ * Definition for binary tree

     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        int maxDepth(TreeNode *root) {
            // Start typing your C/C++ solution below
            // DO NOT write int main() function
            if (root == NULL)
                return 0;
            
            return max(maxDepth(root->left),maxDepth(root->right)) + 1;
        }
    };
  • 相关阅读:
    Spring MVC Ajax 嵌套表单数据的提交
    Spring MVC 过滤静态资源访问
    Spring MVC 页面跳转时传递参数
    IDEA Maven 三层架构 2、运行 springMVC
    IDEA Maven 三层架构 1、基本的Archetype 搭建
    EasyUI DataGrid 基于 Ajax 自定义取值(loadData)
    Spring MVC Ajax 复杂参数的批量传递
    Mybatis Sql片段的应用
    在 Tomcat 8 部署多端口项目
    自动升级的设计思路与实现
  • 原文地址:https://www.cnblogs.com/changchengxiao/p/3413230.html
Copyright © 2011-2022 走看看