• [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;
        }
    };
  • 相关阅读:
    leetcode 13. Roman to Integer
    python 判断是否为有效域名
    leetcode 169. Majority Element
    leetcode 733. Flood Fill
    最大信息系数——检测变量之间非线性相关性
    leetcode 453. Minimum Moves to Equal Array Elements
    leetcode 492. Construct the Rectangle
    leetcode 598. Range Addition II
    leetcode 349. Intersection of Two Arrays
    leetcode 171. Excel Sheet Column Number
  • 原文地址:https://www.cnblogs.com/changchengxiao/p/3413230.html
Copyright © 2020-2023  润新知