一、单值二叉树
两边同时遍历,边遍历边进行比较,完成遍历后返回真,否则为假。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
bool isUnivalTree(struct TreeNode* root)
{
if(root == NULL)
{
return true;
}
if(root->left && root->val != root->left->val)
{
return false;
}
if(root->right && root->val != root->right->val)
{
return false;
}
return isUnivalTree(root->left) && isUnivalTree(root->right);
}
二、二叉树的最大深度
与求深度同理
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int maxDepth(struct TreeNode* root)
{
if(root == NULL)
{
return 0;
}
int leftroot = maxDepth(root->left);
int rightroot = maxDepth(root->right);
return leftroot > rightroot ? leftroot+1 : rightroot+1;
}
三、翻转二叉树
使用后序遍历的思想,先遍历,后调整
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
struct TreeNode* invertTree(struct TreeNode* root)
{
if(root == NULL)
{
return 0;
}
struct TreeNode* leftroot = invertTree(root->left);
struct TreeNode* rightroot = invertTree(root->right);
root->left = rightroot;
root->right = leftroot;
return root;
}
四、相同的树
在递归时每一层函数的栈帧中存在这样的条件:p 为空,q 也为空,返回 true;p 或者 q 只有一个为空,返回 false;p 和 q 的 val 不等,返回 false;否则 p 和 q 的 val 是相等的才递归
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
bool isSameTree(struct TreeNode* p, struct TreeNode* q)
{
if(p == NULL && q == NULL)
{
return true;
}
if(p == NULL || q == NULL)
{
return false;
}
if(p->val != q->val)
{
return false;
}
return isSameTree(p->left,q->left) && isSameTree(p->right,q->right);
}
五、对称二叉树
一棵树对称就是 它的左右子树呈镜像状态。说白了就是节点左子树的值等于右子树的值,右子树的值等于左子树的值。把左右看成两个独立的树
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
bool _isSymmetric(struct TreeNode* Leftroot, struct TreeNode* Rightroot)
{
if(Leftroot == NULL && Rightroot == NULL)
{
return true;
}
if(Leftroot == NULL || Rightroot == NULL)
{
return false;
}
if(Leftroot->val != Rightroot->val)
{
return false;
}
return _isSymmetric(Leftroot->left, Rightroot->right) && _isSymmetric(Leftroot->right, Rightroot->left);
}
bool isSymmetric(struct TreeNode* root)
{
return _isSymmetric(root->left,root->right);