1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution {//p q NULL? 11 public: 12 TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { 13 if(!root || root == p || root == q) return root; 14 TreeNode* l = lowestCommonAncestor(root->left,p,q); 15 TreeNode* r = lowestCommonAncestor(root->right,p,q); 16 // if(!l && !r) return root; 17 // if(l) return r; 18 // return l; 19 return l && r ? root : l ? l : r; 20 } 21 22 23 };
思路:root == p || root == q就return,因为是||,所以实际上是判断p、q是否在当前子树中。
最后一行的? :的意思是:?前的表达式True则执行第一项(root),否则执行:后的一项(l?l:r)。
具体来说就是如果l、r均不为NULL,即左p右q或左q右p,则返回root;如果其中一个为NULL,在返回非NULL的那个节点(l或r)。