From : https://leetcode.com/problems/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
/**
* 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) {
stack<TreeNode *> box;
TreeNode* cur=root;
while(cur) {
if(cur->right && cur->left) box.push(cur->right);
if(cur->left) {
cur->right = cur->left;
cur->left = NULL;
}
cur = cur->right;
if(cur && !cur->left && !cur->right && !box.empty()) {
cur->left = box.top();
box.pop();
}
}
}
};
本文介绍了一种将任意二叉树通过修改指针的方式转换为单链表的方法。该过程不会使用额外的数据结构,并保持节点原有的相对顺序。通过对二叉树的右子树进行暂存和遍历调整左子树来实现这一目标。
831

被折叠的 条评论
为什么被折叠?



