114- Flatten Binary Tree to Linked List

题目

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

If you notice carefully in the flattened tree, each node’s right child points to the next node of a pre-order traversal.

分析
  1. 递归方法:
    自下而上
  2. 非递归方法:自上而下
    1. 从上到下依次寻找左子结点,并且把它挂在右子结点的位置上
    2. 原本的右子结点挂在左子节点的最后一个右子结点上
实现

class Solution {
public:
    void flatten(TreeNode* root) {
    //非递归方法
        if (root == NULL)
            return;
        TreeNode *curr = root, *tmp= NULL;
        while (curr)
        {
            if (curr->left)
            {
                tmp = curr->left;
                while (tmp->right)
                    tmp = tmp->right;
                tmp->right = curr->right;
                curr->right = curr->left;
                curr->left = NULL;
            }
            curr = curr->right;

        }
    }
};

你可能感兴趣的:(Leetcode,算法题解,c++)