求二叉树深度
int maxDepth(TreeNode* root) {
if(!root) return 0;
return dfs(root);
}
int dfs(TreeNode* root){
if(!root) return 0;
int l=dfs(root->left);
int r=dfs(root->right);
return max(l,r)+1;
}
判断是否为平衡二叉树
bool isBalanced(TreeNode* root) {
if(!root) return true;
return abs(depth(root->left)-depth(root->right))<=1&&isBalanced(root->left)&&isBalanced(root->right);
}
int depth(TreeNode* root){
if(!root) return 0;
int l=depth(root->left);
int r=depth(root->right);
return max(l,r)+1;
}
判断二叉树是否对称
bool isSymmetric(TreeNode* root) {
if(!root) return true;
return dfs(root->left,root->right);
}
bool dfs(TreeNode* left,TreeNode* right){
if(!left&&!right) return true;
if(!left||!right||left->val!=right->val) return false;
return dfs(left->left,right->right)&&dfs(left->right,right->left);
}