问题1:判断两二叉树相等
思路:递归实现
/**
* 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 isSameTree(TreeNode* p, TreeNode* q) {
if(p==NULL&&q==NULL)
return true;
if(!p||!q)
return false;
if(p->val==q->val)
return isSameTree(p->left,q->left)&&isSameTree(p->right,q->right);
else
return false;
}
};
问题2:计算二叉树深度
思路:递归实现
/**
* 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:
int TreeDepth(TreeNode* pRoot)
{
if(pRoot==NULL)
return 0;
int leftDepth = TreeDepth(pRoot->left);
int rightDepth = TreeDepth(pRoot->right);
return leftDepth > rightDepth ? (leftDepth + 1) : (rightDepth + 1);
}
};
问题3:二叉树的镜像
思路:递归实现
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
void Mirror(TreeNode *pRoot) {
TreeNode *tmp;
if(pRoot!=NULL){
tmp = pRoot->left;
pRoot->left=pRoot->right;
pRoot->right=tmp;
Mirror(pRoot->left);
Mirror(pRoot->right);
}
}
};