leetcode 104 二叉树的最大深度 (Maximum Depth of Binary Tree)

/**
 * 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) {
        if(root!=NULL){
            return 1+max(maxDepth(root->left),maxDepth(root->right));
        }
        else{
            return 0;
        }
    }
};

别人的代码,不用vector,不过每次要比左右两个。

相当于数组中每个元素和前后比较一下。需要确定前后,i.e.,min,max。 不对。不过,递归到当前节点,不考虑下面时,确实是相当于前后。至于当前节点和下面节点的关系,递归到下面的时候会判断。

class Solution {
public:
    bool isValidBST(TreeNode* root)
    {
        return validateBST(root, LLONG_MIN, LLONG_MAX);
    }
    
private:
    bool validateBST(TreeNode* node, long min, long max)
    {
        if(!node) return true;
//从定义出发,左右节点和当前节点比较;
//左右子树也是BST。左节点小于当前节点,大于当前节点的min。右节点大于当前,小于当前的max。
if(node->val <= min || node->val>=max) return false; return validateBST(node->left, min, node->val) && validateBST(node->right, node->val, max); } };
有道词典
相当于数组中每个 ...
详细X
Equal to each element in the array and compare before and after.

原文地址:https://www.cnblogs.com/azureice/p/leetcode104.html