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
it is actually not to flatten into a linked list but a linked list like tree.
TreeNode* goRightMost(TreeNode* root) {
if(!root) return NULL;
TreeNode* tmp = root;
while(tmp->right) {
tmp = tmp->right;
}
return tmp;
}
void flatten(TreeNode* root) {
if(!root) return;
TreeNode* tmp = root;
while(tmp) {
if(tmp->left) {
TreeNode* rightMost = goRightMost(tmp->left);
rightMost->right = tmp->right;
tmp->right = tmp->left;
tmp->left = NULL;
}
tmp = tmp->right;
}
}
本文介绍了一种将二叉树结构通过特定算法展平为类似链表的树形结构的方法。通过递归地寻找右子树的最右节点,并将其与当前节点的右子树相连,同时将当前节点的左子树赋值给右子树,最后将左子树置空的方式实现了这一转换。该方法可以有效地将任意二叉树结构转换为目标形式。
290

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



