Flatten Binary Tree to Linked List

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

codecss

struct TreeNode
{
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(nullptr), right(nullptr){}
};
class Solution
{
public:
    void flatten(TreeNode* root)
    {
        if(!root)
            return;

        /*
            找到最左子節點,而後回到其父節點,把其父節點和右子節點斷開,將原左子結點連上父節點的右子節點上
            而後再把原右子節點連到新右子節點的右子節點上,而後再回到上一父節點作相同操做
        */
        flatten(root->left);
        flatten(root->right);
        TreeNode *tmp=root->right;
        root->right=root->left;
        root->left=nullptr;
        while(root->right)
            root=root->right;
        root->right=tmp;
    }
};
相關文章
相關標籤/搜索