题目描述:
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
分析:
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
分析:
根据先序优先序列的顺序,全部添加到右子树,左子树全部为空。采用深度优先遍历即可。
/**///8ms/*/
/**
* 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)
return;
TreeNode *cur = root;
stack<TreeNode* > s;
TreeNode *head = new TreeNode(root->val); //添加根节点
TreeNode *tmp = head;
if(root->right != NULL)
s.push(root->right);
if(root->left != NULL)
s.push(root->left);
while(!s.empty()){
cur = s.top();
s.pop();
tmp->left = NULL;
tmp->right = new TreeNode(cur->val);
tmp = tmp->right;
if(cur->right != NULL)
s.push(cur->right);
if(cur->left != NULL)
s.push(cur->left);
}
root ->right = head->right; //将根节点右子树更新为新根节点的右子树,左子树为空
root->left = NULL;
return;
}
};