leetcodeブラシ問題、まとめ、記録、メモ114
1736 ワード
leetcode114
Flatten Binary Tree to Linked List
Given a binary tree, flatten it to a linked list in-place.
For example, Given
The flattened tree should look like:
click to show hints.
Subscribe to see which companies asked this question
このテーマは、とても简単で、、、简単な先序は二叉の木を遍歴して、それからノードをすべて右の木の上でつなぎます.
Flatten Binary Tree to Linked List
Given a binary tree, flatten it to a linked list in-place.
For example, Given
1
/ \
2 5
/ \ \
3 4 6
The flattened tree should look like:
1
\
2
\
3
\
4
\
5
\
6
click to show hints.
Subscribe to see which companies asked this question
このテーマは、とても简単で、、、简単な先序は二叉の木を遍歴して、それからノードをすべて右の木の上でつなぎます.
/**
* 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:
void flatten(TreeNode* root) {
if (root == NULL)
{
return;
}
stack<TreeNode *> st;
st.push(root);
vector<TreeNode *> vt;
while (!st.empty())
{
TreeNode * t = st.top();
st.pop();
vt.push_back(t);
if (t->right)
{
st.push(t->right);
}
if (t->left)
{
st.push(t->left);
}
}
for (int i = vt.size() - 1; i >= 0; --i)
{
if (i == vt.size() - 1)
{
vt[i]->right = NULL;
vt[i]->left = NULL;
}
else
{
vt[i]->right = vt[i + 1];
vt[i]->left = NULL;
}
}
}
};