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);
}
}
};