力扣114. 二叉树展开为链表

  • 思路:
    • 根据二叉树前序遍历:根-左子树-右子树;

    • 要按照前序遍历将二叉树展开,则遍历节点右子树需要挂载到左子树"最右"节点右子树上;

    • 则当前节点 current 左子树 next = current->left 的最右节点 rightmost :
      *

      cpp 复制代码
      TreeNode* rightmost = next;
      while (rightmost->right != nullptr) {
          rightmost = rightmost->right;
      }
    • 将当前节点右子树挂载到左子树"最右"节点的右子树上:rightmost->right = current->right;

    • 则当前节点 current 展开完成,将其左子树按照要求置 nullptr,右子树挂载其左子树节点:current->left = nullptr;current->right = next;

    • 迭代下一个需要展开的节点对应的树;

cpp 复制代码
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    void flatten(TreeNode* root) {
        TreeNode *current = root;
        while (current != nullptr) {
            if (current->left != nullptr) {
                TreeNode* next = current->left;
                TreeNode* rightmost = next;
                while (rightmost->right != nullptr) {
                    rightmost = rightmost->right;
                }
                rightmost->right = current->right;

                current->left = nullptr;
                current->right = next;
            }

            current = current->right;
        }
    }
};
相关推荐
colus_SEU13 分钟前
【编译原理笔记】2.1 Programming Language Basics
c++·算法·编译原理
人工智能培训20 分钟前
大模型-去噪扩散概率模型(DDPM)采样算法详解
算法
Excuse_lighttime24 分钟前
只出现一次的数字(位运算算法)
java·数据结构·算法·leetcode·eclipse
liu****25 分钟前
笔试强训(二)
开发语言·数据结构·c++·算法·哈希算法
无限进步_1 小时前
扫雷游戏的设计与实现:扫雷游戏3.0
c语言·开发语言·c++·后端·算法·游戏·游戏程序
qq_433554541 小时前
C++ 完全背包
开发语言·c++·算法
lingran__1 小时前
算法沉淀第二天(Catching the Krug)
c++·算法
im_AMBER2 小时前
杂记 15
java·开发语言·算法
爱coding的橙子2 小时前
每日算法刷题Day70:10.13:leetcode 二叉树10道题,用时2h
算法·leetcode·深度优先
ghie90903 小时前
基于MATLAB的遗传算法优化支持向量机实现
算法·支持向量机·matlab