您的位置:首页 > 其它

Flatten Binary Tree to Linked List [LeetCode]

2013-11-27 15:15 218 查看
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.

Hints:
If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal.

Solution:

void flatten(TreeNode *root) {
stack<TreeNode *> nodes;
if(root == NULL)
return;
nodes.push(root);
TreeNode * pre = root;
while(nodes.size() != 0){
TreeNode * node = nodes.top();
nodes.pop();
if(node->right != NULL)
nodes.push( node->right);
if(node->left != NULL)
nodes.push( node->left);
pre->left = NULL;
if(node != root){
pre->right = node;
pre = pre->right;
}

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