您的位置:首页 > 其它

Flatten Binary Tree to Linked List - LeetCode 114

2015-06-15 20:29 411 查看
题目描述:

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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: