1. 二叉树最低公共父节点
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if (!root) return NULL;
if (root == p || root == q) return root;
TreeNode* left = lowestCommonAncestor(root->left, p, q);
TreeNode* right = lowestCommonAncestor(root->right, p, q);
if (left && right) return root;
else if (!left && right) return right;
else if (left && !right) return left;
else return NULL;
}
2. 对称二叉树
bool func(TreeNode* pLeft, TreeNode* pRight);
bool isSymmetrical(TreeNode* root)
{
if (!root) return true;
return func(root->left, root->right);
}
bool func(TreeNode* pLeft, TreeNode* pRight)
{
if (!pLeft && !pRight) return true;
if (pLeft && !pRight || !pLeft && pRight) return false;
if (pLeft->val != pRight->val) return false;
return func(pLeft->left, pRight->right) && func(pLeft->right, pRight->left);
}
3. 层序打印二叉树
vector<vector<int> > print(TreeNode* pRoot)
{
vector<vector<int> > res;
if (!pRoot) return res;
queue<TreeNode*> que1;
queue<TreeNode*> que2;
queue<TreeNode*>* p1 = &que1;
queue<TreeNode*>* p2 = &que2;
p1->push(pRoot);
vector<int> vec;
while (!p1->empty())
{
TreeNode* temp = p1->front();
p1->pop();
if (temp->left) p2->push(temp->left);
if (temp->right) p2->push(temp->right);
vec.push_back(temp->val);
if (p1->empty())
{
res.push_back(vec);
vec.clear();
queue<TreeNode*>* p = p1;
p1 = p2;
p2 = p;
}
}
return res;
}