首页 > 技术文章 > 114. Flatten Binary Tree to Linked List(M)

guxuanqing 2019-01-27 17:50 原文

114. 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:
    TreeNode* prev = NULL;
    void flatten(TreeNode* root) {
        //using this solution: https://leetcode.com/problems/flatten-binary-tree-to-linked-list/discuss/36977/My-short-post-order-traversal-Java-solution-for-share
        if(root == NULL)
            return;
        flatten(root->right);
        flatten(root->left);
        root->left = NULL;
        root->right = prev;
        prev = root;
        
        
        
    }
};

 

推荐阅读