欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

LeetCode: 114. Flatten Binary Tree to Linked List

程序员文章站 2022-03-07 23:40:14
...

LeetCode: 114. 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

题目大意: 将给定的二叉树拉直成链表形式。

解题思路 —— 递归求解

先将左子树和右子树拉直成链表形式,然后将它们合并成一条链表。如:

  • 原始二叉树
    LeetCode: 114. Flatten Binary Tree to Linked List

  • flatten(root->left): 拉直左子树
    LeetCode: 114. Flatten Binary Tree to Linked List

  • flatten(root->right):拉直右子树
    LeetCode: 114. Flatten Binary Tree to Linked List

  • 合并左右子树
    将右子树链接到左子树
    LeetCode: 114. Flatten Binary Tree to Linked List
    将左子树移动到右边
    LeetCode: 114. Flatten Binary Tree to Linked List

AC 代码

/**
 * 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) {
        if(root == nullptr) return;

        // 分别对左右孩子处理
        flatten(root->left);
        flatten(root->right);

        // 将右边孩子链接在左孩子后面
        // 然后将左孩子移到右边
        TreeNode** leftChildTreeLeaf = &(root->left);
        while(*leftChildTreeLeaf != nullptr)
        {
            leftChildTreeLeaf = &(*leftChildTreeLeaf)->right;
        }
        *leftChildTreeLeaf = root->right;
        root->right = root->left;
        root->left = nullptr;
    }
};