题意:找两个结点的最近公共祖先。
思路:DFS。
/**
* 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:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(!root) return NULL;
if(p == root || q == root) return root;
if(root->right == p && root->left == q) return root;
if(root->right == q && root->left == p) return root;
if(root->left == q) return q;
if(root->left == p) return p;
TreeNode *left = NULL;
TreeNode *right = NULL;
left = lowestCommonAncestor(root->left, p, q);
right = lowestCommonAncestor(root->right, p, q);
if(left == p && right == q) return root;
if(left == q && right == p) return root;
if(left) return left;
if(right) return right;
return NULL;
}
};