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;
        }
    };
  • 相关阅读:
    Web开发者需具备的8个好习惯
    全球十大搜索引擎排名
    ContextWrapper
    PackageManager
    重写equals方法的注意事项
    StackOverflow 并不只是一个问答网站
    android 中ids.xml资源的使用
    The method dismissDialog(int) from the type Activity is deprecated
    百度员工离职总结:如何做个好员工?
    Mysql 自动化任务
  • 原文地址:https://www.cnblogs.com/changchengxiao/p/3413230.html
Copyright © 2011-2022 走看看