Given a binary tree, flatten it to a linked list in-place.
For example, given the following tree:
1
/ \
2 5
/ \ \
3 4 6
The flattened tree should look like:
1
\
2
\
3
\
4
\
5
\
6
将一棵二叉树转化为linked list
前序遍历,将root的右节点放置到左节点最后一个右子节点下方,递归遍历。
/**
* 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) {
while(root){
TreeNode* cur;
if(root->left){
cur = root->left;
while(cur->right){
cur = cur->right;
}
cur->right = root->right;
root->right = root->left;
root->left = NULL;
}
root = root->right;
}
}
};