题目:
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
Hints:
If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal.
/**
* Definition for binary tree
* 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 == NULL)
return;
TreeNode *right = root->right;
if(lastVisited != NULL) {
lastVisited->left = NULL;
lastVisited->right = root;
}
lastVisited = root;
flatten(root->left);
flatten(right);
}
private:
TreeNode *lastVisited = NULL;
};
本文介绍了一种将二叉树结构通过先序遍历的方式展平为链表的方法,并提供了一个C++实现示例。在展平后的树中,每个节点的右子节点指向先序遍历序列中的下一个节点。
833

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



