Skip to content

Commit a1e6de5

Browse files
Update Lowest_Common_Ancestor_of_a_Binary_Tree.cpp
1 parent 0c67f0b commit a1e6de5

File tree

1 file changed

+81
-1
lines changed

1 file changed

+81
-1
lines changed

Lowest Common Ancestor of a Binary Tree/Lowest_Common_Ancestor_of_a_Binary_Tree.cpp

+81-1
Original file line numberDiff line numberDiff line change
@@ -98,4 +98,84 @@ class Solution
9898

9999
return *iter1;
100100
}
101-
};
101+
};
102+
103+
// 另外一种写法
104+
// Runtime: 24 ms, faster than 43.62% of C++ online submissions for Lowest Common Ancestor of a Binary Tree.
105+
// Memory Usage: 18.2 MB, less than 18.89% of C++ online submissions for Lowest Common Ancestor of a Binary Tree.
106+
107+
/**
108+
* Definition for a binary tree node.
109+
* struct TreeNode {
110+
* int val;
111+
* TreeNode *left;
112+
* TreeNode *right;
113+
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
114+
* };
115+
*/
116+
class Solution
117+
{
118+
public:
119+
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q)
120+
{
121+
// 边界条件处理
122+
if (root == nullptr || q == nullptr || p == nullptr)
123+
return nullptr;
124+
125+
vector<TreeNode*> path1, path2;
126+
getPath(path1, root, p);
127+
getPath(path2, root, q);
128+
129+
return find(path1, path2);
130+
}
131+
private:
132+
void getPath(vector<TreeNode*>& path, TreeNode* root, TreeNode* target)
133+
{
134+
path.push_back(root);
135+
136+
TreeNode* preNode = nullptr;
137+
stack<TreeNode*> treeStack;
138+
139+
while (root || !treeStack.empty())
140+
{
141+
while (root)
142+
{
143+
path.push_back(root);
144+
treeStack.push(root);
145+
root = root->left;
146+
}
147+
if (!treeStack.empty())
148+
{
149+
root = treeStack.top();
150+
treeStack.pop();
151+
152+
if (root->right == nullptr || root->right == preNode)
153+
{
154+
if (root == target)
155+
return ;
156+
path.pop_back();
157+
preNode = root;
158+
root = nullptr;
159+
}
160+
else
161+
{
162+
treeStack.push(root);
163+
root = root->right;
164+
}
165+
}
166+
}
167+
}
168+
169+
TreeNode* find(vector<TreeNode*>& path1, vector<TreeNode*>& path2)
170+
{
171+
TreeNode* res = path1.front();
172+
for (int i = 0; i < path1.size() && i < path2.size(); )
173+
{
174+
if (i + 1 < path1.size() && i + 1 < path2.size() && path1[i + 1] == path2[i + 1])
175+
++i, res = path1[i];
176+
else
177+
break;
178+
}
179+
return res;
180+
}
181+
};

0 commit comments

Comments
 (0)