lintcode maximum-depth-of-binary-tree 二叉树的最大深度

来源:互联网 发布:mac opengl include 编辑:程序博客网 时间:2024/05/16 08:59

问题描述

lintcode

笔记

代码

/** * Definition of TreeNode: * class TreeNode { * public: *     int val; *     TreeNode *left, *right; *     TreeNode(int val) { *         this->val = val; *         this->left = this->right = NULL; *     } * } */class Solution {public:    /**     * @param root: The root of binary tree.     * @return: An integer     */    int maxDepth(TreeNode *root) {        // write your code here        if (root == NULL)            return 0;        if (root->left == NULL && root->right != NULL)            return maxDepth(root->right) + 1;        if (root->left != NULL && root->right == NULL)            return maxDepth(root->left) + 1;        if (root->left == NULL && root->right == NULL)            return 1;        if (root->left != NULL && root->right != NULL)        {            int left = maxDepth(root->left);            int right = maxDepth(root->right);            if (left > right)                return left+1;            else                return right+1;        }    }};

二次练习

/** * Definition of TreeNode: * class TreeNode { * public: *     int val; *     TreeNode *left, *right; *     TreeNode(int val) { *         this->val = val; *         this->left = this->right = NULL; *     } * } */class Solution {public:    /**     * @param root: The root of binary tree.     * @return: An integer     */    int maxDepth(TreeNode *root) {        // write your code here        if (root == NULL)            return 0;        return max(maxDepth(root->left), maxDepth(root->right)) + 1;    }};
0 0
原创粉丝点击