判断一颗二叉树是是否是另一颗树的子树
class Solution {
public:
bool test(TreeNode* T1,TreeNode* T2)
{
if(T1==NULL && T2==NULL)
return true;
if(T1==NULL||T2==NULL||T1->val!=T2->val)
return false;
return test(T1->left,T2->left)&&test(T1->right,T2->right);
}
bool isSubtree(TreeNode *T1, TreeNode *T2) {
// write your code here
if( T2==NULL )
return true;
if(T1==NULL)
return false;
if(T1->val==T2->val)
{
if(test(T1,T2))
return true;
}
return isSubtree(T1->left,T2)||isSubtree(T1->right,T2);
}
};
判断一棵树是否是完全二叉树
bool istree(TreeNode* root)
{
queue<TreeNode*> q;
q.push(root);
int count = 1;
int isbintree = 1;
while (!q.empty())
{
count = q.size();
while (count--)
{
Node* tmp = q.front();
q.pop();
cout << tmp->val << endl;
if (tmp->left)
{
if (isbintree == 0)
return false;
q.push(tmp->left);
}
else
isbintree = 0;
if (tmp->right)
{
if (isbintree == 0)
return false;
q.push(tmp->right);
}
else
isbintree = 0;
}
}
return true;
}
二叉树中两个节点的最近公共祖先
要求考虑以下三种种情况,给出解决方案,并解决:
1:二叉树每个节点有parent(三叉链)
相当于转换成链表求交点问题
2:二叉树是搜索二叉树。
直接找比他们最大还大的节点
3:就是普通二叉树。(尽可能实现时间复杂度为(N ))
通过路径来求
class Solution {
public:
/**
* @param root: The root of the binary search tree.
* @param A and B: two nodes in a Binary.
* @return: Return the least common ancestor(LCA) of the two nodes.
*/
bool GetNodePath(TreeNode* cur, TreeNode* node, vector<TreeNode*>& l)
{
if (cur == node)
{
l.push_back(cur);
return true;
}
if(cur==NULL)
return false;
l.push_back(cur);
bool found = false;
if (!found && cur->left)
found = GetNodePath(cur->left, node, l);
if (!found && cur->right)
found = GetNodePath(cur->right, node, l);
if (!found)
l.pop_back();
return found;
}
TreeNode *lowestCommonAncestor(TreeNode *root, TreeNode *A, TreeNode *B) {
// write your code here
if(root==A||root==B||root==NULL)
return root;
vector<TreeNode*> path1;
GetNodePath(root,A,path1);
vector<TreeNode*> path2;
GetNodePath(root,B,path2);
int size=path1.size()>path2.size()?path2.size():path1.size();
int i=0;
TreeNode* ret=NULL;
for(;i<size;i++)
{
if(path1[i]==path2[i])
ret=path1[i];
else
break;
}
return ret;
}
};