20200716笔记(1.N 叉树的最大深度2.检查网格中是否存在有效路径3.验证二叉搜索树)

1.N 叉树的最大深度
类似于二叉树的深度
二叉树的深度是我自己写的
深度优先搜索DFS函数

/*
// Definition for a Node.
class Node {
public:
    int val;
    vector<Node*> children;

    Node() {}

    Node(int _val) {
        val = _val;
    }

    Node(int _val, vector<Node*> _children) {
        val = _val;
        children = _children;
    }
};
*/

class Solution {
public:
    int maxDepth(Node* root) {
        if(root==NULL){return 0;}
        int maxlen=0;
        for(int i=0;i<root->children.size();i++){
            int len=maxDepth(root->children[i]);
            maxlen=max(maxlen,len);
        }
        return maxlen+1;
    }
};

二叉树的深度是这样的 自己写的

class Solution {
public:
    int maxDepth(TreeNode* root) {
        return DFS(root,0);
    }
    int DFS(TreeNode* node,int count){
        if(node==NULL){return count;}
        return max(DFS(node->left,count+1),DFS(node->right,count+1));
    }
};

2.检查网格中是否存在有效路径
有点小复杂 没看懂

3.验证二叉搜索树
这道题 其实你要知道二叉搜索树就是左中右这样的顺序的
所以二叉搜索树的中序遍历是有序的 那么我们只需把中序遍历写出来 然后判断即可

/**
 * 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:
    bool isValidBST(TreeNode* root) {
        if(root==NULL){return true;}
        vector<int>res;
        rec(root,res);
        for(int i=0;i<res.size()-1;i++){
            if(res[i]>=res[i+1]){return false;}
        }
        return true;
    }
    void rec(TreeNode* root,vector<int>&ret){
        if(root!=NULL){
            rec(root->left,ret);
            ret.push_back(root->val);
            rec(root->right,ret);
        }
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值