目录
对称二叉树
用递归的方法去判断对称两节点
bool compare(TreeNode* left,TreeNode* right)
{
//一定要先判断两端节点空的情况
if(left==NULL&&right==NULL) return true;
else if((left!=NULL&&right==NULL)||(left==NULL&&right!=NULL)) return false;
else if(left->val!=right->val) return false;
else return compare(left->left,right->right)&&compare(left->right,right->left);
}
bool isSymmetric(TreeNode* root)
{
//判断根节点是否为空
if(root==NULL) return true;
//开始递归判断左右节点
return compare(root->left,root->right);
}
二叉树最大深度
思路:一个节点求深度函数+求取每次左右节点深度最大值
递归思想:
int deepth(TreeNode* node)
{
if(node==NULL) return 0;
int leftdeep=deepth(node->left);
int rightdeep=deepth(node->right);
int ans=1+max(leftdeep,rightdeep);
return ans;
}
int maxDepth(TreeNode* root)
{
if(root==NULL) return 0;
else return deepth(root);
}
简化代码:
int maxDepth(TreeNode* root)
{
if(root==NULL) return 0;
else return 1+max(maxDepth(root->left),maxDepth(root->right));
}
N叉树最大深度
int maxDepth(Node* root) {
if(root==NULL) return 0;
int ans=0;
for(int i=0;i<root->children.size();i++){
ans=max(ans,maxDepth(root->children[i]));
}
return ans+1;
}
二叉树的最小深度
思路以及关键点:最小深度需要一个节点的左右两个子节点都为空,否则继续递归不为空节点的最小值
精简代码:
int minDepth(TreeNode* root)
{
if(root==NULL) return 0;
if(root->left==NULL&&root->right!=NULL) {
return 1+minDepth(root->right);
}
if(root->left!=NULL&&root->right==NULL) {
return 1+minDepth(root->left);
}
return 1+min(minDepth(root->left),minDepth(root->right));
}