算法-数据结构之二叉树
1.翻转二叉树
在翻转问题中总结了
地址:http://www.cnblogs.com/vhyz/p/7241743.html
2.判断二叉树是否相等
2.1 100. Same Tree
Given two binary trees, write a function to check if they are equal or not.
Two binary trees are considered equal if they are structurally identical and the nodes have the same value.
2.2算法初步
利用递归的思路,若两者不同时为空,则返回false,若同时为空,则返回true
因为如果进行到了最后一步都为空,那么一定为true
/**
* 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==nullptr)^(q==nullptr)))
return false;
if(p==nullptr&&q==nullptr)
return true;
if(p->val==q->val)
return (isSameTree(p->left,q->left)&&isSameTree(p->right,q->right));
else return false;
}
};
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 isSameTree(TreeNode* p, TreeNode* q) {
if(p==nullptr||q==nullptr)
return p==q;
return (p->val==q->val&&isSameTree(p->left,q->left)&&isSameTree(p->right,q->right));
}
};
3.判断是否为镜面二叉树
3.1 题目 Symmetric Tree
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree [1,2,2,3,4,4,3] is symmetric:
1
/
2 2
/ \ /
3 4 4 3
But the following [1,2,2,null,3,null,3] is not:
1
/
2 2
\
3 3
3.2 queue算法
class Solution {
public:
bool isSymmetric(TreeNode* root) {
if(root==nullptr)
return true;
queue<TreeNode*>s1,s2;
TreeNode*left,*right;
s1.push(root->left);
s2.push(root->right);
while(!s1.empty()&&!s2.empty())
{
left=s1.front();
s1.pop();
right=s2.front();
s2.pop();
if(left==nullptr&&right==nullptr)
continue;
if(left==nullptr||right==nullptr)
return false;
if(left->val!=right->val)
return false;
s1.push(left->left);
s1.push(left->right);
s2.push(right->right);
s2.push(right->left);
}
return true;
}
};