leetcode114
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
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;
}
}
}
};