题目:
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
思路:
思路也很简单:首先分别平坦化左子树和右子树,然后将左子树接在根节点和右子树之间即可。在实现的过程中,一定不能忘记在移动左子树之后,将根节点的左子树指针置位NULL。
代码:
/**
* 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;
}
flatten(root->left);
flatten(root->right);
TreeNode *right = root->right;
root->right = root->left;
root->left = NULL;
while(root->right) {
root = root->right;
}
root->right = right;
}
};
本文介绍了一种将二叉树结构通过简单的算法展平为链表的方法。核心思路在于递归地展平左右子树,并调整指针使左子树位于根节点与右子树之间。
832

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



