Flatten Binary Tree to Linked List

来源:互联网 发布:淘宝双十一数据 编辑:程序博客网 时间:2024/06/06 09:50

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.
将左子树插入到root和其右子树之间。

void flatten(TreeNode *root){    if (root==NULL)        return;    TreeNode* left = root->left;    TreeNode* right = root->right;    if (left)    {        root->right = left;        root->left = NULL;        TreeNode* rightmost = left;        while(rightmost->right)        {            rightmost = rightmost->right;        }        rightmost->right = right;    }    flatten(root->right);}



0 0