1.求两个节点的最近公共父亲节点(只有左右孩子节点)。
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
void destroy(TreeNode* head) {
if (head) {
destroy(head->left);
destroy(head->right);
delete head;
head = nullptr;
}
}
};
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if (root == nullptr)
return nullptr;
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;
return left ? left : right;
}
};
2.求24点。