Leetcode 114. Flatten Binary Tree to Linked List

时间:2019-02-11
本文章向大家介绍Leetcode 114. Flatten Binary Tree to Linked List,主要包括Leetcode 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

题目链接:https://leetcode.com/problems/flatten-binary-tree-to-linked-list/

思路:把当前根节点root的right子树,连接到当前节点root的左子树的最右子树,看图:绿色的子树挂到黄色区域

/**
 * 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 *t=root;
        while(t)
        {
            if(t->left)
            {
                TreeNode *node=t->left;
                while(node->right)
                {
                    node=node->right;
                } 
                node->right=t->right;
                
                t->right=t->left;
                t->left=NULL;
            }
            t=t->right;
        }
    }
};