Given a binary tree, flatten it to a linked list in-place.
For example,
Given
The flattened tree should look like:
本题也是考察二叉树和指针操作的题目。题目要求将一棵二叉树拉平为一个链表 。链表通过树节点的右子树相连,且展开的顺序为原来树的前序遍历。
实现思路:
需要注意的是,对处理后的左子树指针需要设置为NULL。
/**
* 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;
if (root->left != NULL)
{
TreeNode *left = root->left;
while(left->right)
{
left = left->right;
}
left->right = root->right;
root->right = root->left;
root->left = NULL;
}
flatten(root->right);
}
};
LeetCode (15) Flatten Binary Tree to Linked List
原文地址:http://blog.csdn.net/angelazy/article/details/45117275