LeetCode-114-Flatten Binary Tree to Linked List

Posted 无名路人甲

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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

解题思路:从题目可以看出,用后续遍历可以解决问题。用一个全局变量存储上一个访问的点,将上一个访问的点挂在右边子树上,并将左边的子树清空。

    TreeNode* prev=nullptr;
    void flatten(TreeNode* root) {
        if(root==nullptr) return;
        flatten(root->right);
        flatten(root->left);
        root->right = prev;
        root->left = nullptr;
        prev = root;
    }

 

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

LeetCode 114. Flatten Binary Tree to Linked List

leetcode--114. Flatten Binary Tree to Linked List

LeetCode 114. Flatten Binary Tree to Linked List

Leetcode 114, Flatten Binary Tree to Linked List

LeetCode-114-Flatten Binary Tree to Linked List

LeetCode 114 Flatten Binary Tree to Linked List