#Leetcode# 114. Flatten Binary Tree to Linked List

https://leetcode.com/problems/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

代码:

/**
 * 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) {
        if(!root) return;
        flatten(root -> left);
        flatten(root -> right);
        
        TreeNode* R = root -> right;
        root -> right = root -> left;
        root -> left = NULL;
        TreeNode* cur = root;
        while(cur -> right) cur = cur -> right;
        cur -> right = R;
    }
};

  好像一个世纪那么久没写 LC 了  

posted @ 2018-12-22 10:39  丧心病狂工科女  阅读(95)  评论(0编辑  收藏  举报