/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ /*寻找公共祖先结点LCA算法de思想: 第零种情况:root为null时直接return 第一种情况:如果p在左子树q在右子树或反之则root为LCA 第二种情况:p和q均在左子树(LCA递归左子树) 第三种情况:p和q均在右子树(LCA递归右子树) PS:最后return的right和left不会同时为NULL */ class Solution { public: TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { if(root==NULL||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{ return left==NULL?right:left; } } };
/** * 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 == NULL || root == p || root == q){ return root; } //将题目简化为查找以root为根结点的二叉树上是否有p或q节点,有则返回root //递归左子树 TreeNode* left = lowestCommonAncestor(root->left, p, q); //递归右子树 TreeNode* right = lowestCommonAncestor(root->right, p, q); if(left && right){ //左右子树上均能找到p或q,即p和q分居左右子树,直接返回root return root; }else{ //最后的right和left不会同时为NULL return left == NULL? right: left; } } };