Leetcode题目: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

题目解答:

这个题目是将一个二叉树变成一个通过右子节点链接的链表。可以发现的是,变化后右子树整体都在左子树的后面。所以可以先变头,再变左,再变右。我们需要把右子树给暂存起来。

在处理完当前的根节点之后,把左子树链在右边,再接着依次处理它的右节点。

代码:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    void flatten(TreeNode* root) {
        TreeNode *curNode = root;
        while(curNode != NULL)
        {
            TreeNode *pre = curNode -> left;
            TreeNode *tmp = curNode -> right;
            curNode -> left = NULL;

            if(pre != NULL)
            {
                curNode -> right = pre;
                while(pre -> right != NULL)
                {
                    pre = pre -> right;
                }
                pre -> right = tmp;
            }
            curNode = curNode -> right;
        }
    }
};

  

posted @ 2016-06-01 14:15  CodingGirl121  阅读(92)  评论(0编辑  收藏  举报