[LeetCode] Flatten Binary Tree to Linked List

Posted mthoutai

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] Flatten Binary Tree to Linked List相关的知识,希望对你有一定的参考价值。

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

click to show hints.

Hints:

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

解题思路:

题意为将二叉树依照先序遍历压平。

最開始时对in-place理解错误,以为空间复杂度仅仅能为O(1)。事实上不然(我们姑且觉得递归的时候空间不变)。

我们能够用递归来解决问题。

首先定义个递归函数,改递归函数返回root为根节点的最右节点。

倘若root->left不为空。则将左子树的节点插入到root->right中。

递归代码例如以下:

/**
 * 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) {
        flattenHelper(root);
    }
    
    //返回root为根的最右边的那个节点
    TreeNode* flattenHelper(TreeNode* root){
        if(root == NULL){
            return NULL;
        }
        TreeNode* leftMost = flattenHelper(root->left);
        TreeNode* rightMost = flattenHelper(root->right);
        if(leftMost!=NULL){
            TreeNode* temp = root->right;
            root->right = root->left;
            root->left = NULL;
            leftMost->right = temp;
        }
        
        if(leftMost==NULL&&rightMost==NULL){
            return root;
        }else if(rightMost==NULL){
            return leftMost;
        }else{
            return rightMost;
        }
    }
};






以上是关于[LeetCode] Flatten Binary Tree to Linked List的主要内容,如果未能解决你的问题,请参考以下文章

[LeetCode] Flatten Binary Tree to Linked List

leetcode 114. Flatten Binary Tree to Linked List (Python版)

Leetcode 之Flatten Binary Tree to Linked List(50)

LeetCode 114. Flatten Binary Tree to Linked List

leetcode Flatten Binary Tree to Linked List

leetcode--114. Flatten Binary Tree to Linked List