您的位置:首页 > 其它

LeetCode OJ - Flatten Binary Tree to Linked List

2014-09-12 23:21 204 查看
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


click to show hints.
分析:root -> left -> right 其中root->right一定是指向原来的左子树,而原来的左子树最后一个元素指向原来的右子树,第一次得到下面的结果



接着以2为root节点,继续调整下面的树,整个过程可以形成递归,当然也可以用迭代来做

/**
* 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 ;
while(root) {
if(root->left) {
TreeNode *p = root->left;
//寻找左子树“最后”一个节点
while(p->right) p = p->right;
//根、左子树、右子树的连接
p->right = root->right;
root->right = root->left;
root->left = NULL;
}

root = root->right;
}
}
};

下面是递归代码:

/**
* 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 ;
Adjust(root);
}

void Adjust(TreeNode * root) {
if(root == NULL) return ;

if(root->left) {
TreeNode *p = root->left;
//寻找左子树“最后”一个节点
while(p->right) p = p->right;
//根、左子树、右子树的连接
p->right = root->right;
root->right = root->left;
root->left = NULL;
}

Adjust(root->right);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: