leetcode 236 二叉树的最近公共祖先
做完了发现好像是个并不困难的递归。其实就是两种情况,最近公共祖先是两个中的一个或者不是两个中的一个。设置三个bool变量,两个指示子树有没有东西,一个指示自身是不是,再按照规律判断就行了。逻辑很清晰,不知道为什么自己做了那么久,贴代码
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 { 11 public: 12 TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) 13 { 14 P = p; 15 Q = q; 16 dfs(root); 17 return res; 18 } 19 private: 20 TreeNode* P; 21 TreeNode* Q; 22 TreeNode* res; 23 bool dfs(TreeNode* root) 24 { 25 if(!root) 26 return false; 27 bool ifLeft = false; 28 bool ifRight = false; 29 bool ifSelf = false; 30 if(root == P || root == Q) 31 ifSelf = true; 32 if(dfs(root->left)) 33 ifLeft = true; 34 if(dfs(root->right)) 35 ifRight = true; 36 //根据递归结果判断 37 if(ifSelf) 38 { 39 //本身是其中一节点并且另一节点在两边 40 if(ifLeft || ifRight) 41 { 42 res = root; 43 return true; 44 } 45 //本身是但两边没有 46 else 47 return true; 48 } 49 else 50 { 51 //分布在两边,那当前节点就是答案 52 if(ifLeft && ifRight) 53 res = root; 54 //两边有一个,保你一条命 55 else if(ifLeft || ifRight) 56 return true; 57 else 58 return false; 59 } 60 return false; 61 } 62 };
还有一种方法是首先遍历所有的节点,并且存储所有节点的父节点。然后再访问p的所有父节点并存储,之后对q节点同样的操作,一旦遇到一个同样存在于p节点祖先中的,就认为是最深的父节点,贴代码
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 { 11 public: 12 unordered_map<int,TreeNode*> fa; 13 unordered_map<int,bool> vis; 14 TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) 15 { 16 fa[root->val] = NULL; 17 dfs(root); 18 while(p) 19 { 20 vis[p->val] = true; 21 p = fa[p->val]; 22 } 23 while(q) 24 { 25 if(vis[q->val]) 26 return q; 27 q = fa[q->val]; 28 } 29 return NULL; 30 } 31 void dfs(TreeNode* root) 32 { 33 if(root->left) 34 { 35 fa[root->left->val] = root; 36 dfs(root->left); 37 } 38 if(root->right) 39 { 40 fa[root->right->val] = root; 41 dfs(root->right); 42 } 43 } 44 };

浙公网安备 33010602011771号