leetcode 114. 二叉树展开为链表(Flatten Binary Tree to Linked List)

Posted zhanzq

tags:

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

题目描述:

给定一个二叉树,原地将它展开为链表。

示例:

给定二叉树

    1
   /   2   5
 / \   3   4   6

将其展开为:

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, TreeNode*& head, TreeNode*& tail){
        if(root == NULL){
            return;
        }else{
            head = root;
            TreeNode* lhead = NULL, * ltail = NULL;
            TreeNode* rhead = NULL, * rtail = NULL;
            if(root->left == NULL && root->right == NULL){
                // leaf node
                tail = root;
            }else if(root->left == NULL){
                flatten(root->right, rhead, rtail);
                tail = rtail;
                root->left = NULL;
                root->right = rhead;
            }else if(root->right == NULL){
                flatten(root->left, lhead, ltail);
                tail = ltail;
                root->left = NULL;
                root->right = lhead;
            }else{
                flatten(root->left, lhead, ltail);
                flatten(root->right, rhead, rtail);
                ltail->left = NULL;
                ltail->right = rhead;
                tail = rtail;
                root->left = NULL;
                root->right = lhead;
            }
        }
    }
    
    void flatten(TreeNode* root) {
        TreeNode* head = NULL, * tail = NULL;
        flatten(root, head, tail);
        root = head;
    }
};

以上是关于leetcode 114. 二叉树展开为链表(Flatten Binary Tree to Linked List)的主要内容,如果未能解决你的问题,请参考以下文章

leetcode 114. 二叉树展开为链表(dfs)

[LeetCode] 114. 二叉树展开为链表 ☆☆☆(深度遍历)

[LeetCode] 114. 二叉树展开为链表

LeetCode(114): 二叉树展开为链表

LeetCode第114题—二叉树展开为链表—Python实现

Leetcode No.114 二叉树展开为链表