标签:
1 class Solution { 2 public: 3 TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { 4 if (!root || root == p || root == q) return root; // 注意边界条件这里的意义 5 else { 6 TreeNode* left = lowestCommonAncestor(root->left, p, q); 7 TreeNode* right = lowestCommonAncestor(root->right, p, q); 8 if (left && right) return root; // 注意这里,左右都不为空,说明p,q分布在左右两个子树 9 else if (! left) return right; 10 else return left; 11 } 12 } 13 };
下面的代码在codeblocks测试通过,leetcode oj上不过,不过出错的样列在codeblocks上都能过:
1 TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { 2 // 深度优先遍历,生成两个单链表,求两个单链表的最后一个公共节点 3 if (p == nullptr || q == nullptr) return (p == nullptr) ? q : p; 4 vector<TreeNode*> vec1, vec2; 5 TreeNode* curr = root; 6 bool flag = false; 7 while (true) { // 深搜构造链表 8 while (curr != nullptr) { 9 vec1.push_back(curr); 10 if (curr == p) { 11 flag = true; break; 12 } 13 curr = curr->left; 14 } 15 if (curr != p) { 16 TreeNode* temp = new TreeNode(-1); 17 while (vec1.back()->right == nullptr || vec1.back()->right == temp) { // 后一个条件防止当前节点的右儿子是刚弹出的节点 18 temp = vec1.back(); 19 vec1.pop_back(); 20 } 21 delete temp; 22 curr = vec1.back()->right; 23 } 24 if (flag) break; 25 } 26 curr = root; 27 flag = false; 28 while (true) { 29 while (curr != nullptr) { 30 vec2.push_back(curr); 31 if (curr == q) { 32 flag = true; break; 33 } 34 curr = curr->left; 35 } 36 if (curr != q) { 37 TreeNode* temp = new TreeNode(-1); 38 while (vec2.back()->right == nullptr || vec2.back()->right == temp) { 39 temp = vec2.back(); 40 vec2.pop_back(); 41 } 42 delete temp; 43 curr = vec2.back()->right; 44 } 45 if (flag) break; 46 } 47 int i = 0; 48 while (i < vec1.size() && i < vec2.size()) { 49 if(vec1[i]->val == vec2[i]->val) ++ i; 50 else break; 51 } 52 return vec1[i - 1]; 53 }
236. Lowest Common Ancestor of a Binary Tree
标签:
原文地址:http://www.cnblogs.com/shadowwalker9/p/5751317.html