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

Leetcode 114. Flatten Binary Tree to Linked List

程序员文章站 2022-03-04 19:05:10
...

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Leetcode 114. Flatten Binary Tree to Linked List

2. Solution

/**
 * 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) {
            return;
        }
        vector<TreeNode*> nodes;
        preorderTranverse(nodes, root);
        for(int i = 0; i < nodes.size() - 1; i++) {
            nodes[i]->left = nullptr;
            nodes[i]->right = nodes[i + 1];
        }
        nodes[nodes.size() - 1]->left = nullptr;
        nodes[nodes.size() - 1]->right = nullptr;
    }

private:
    void preorderTranverse(vector<TreeNode*>& nodes, TreeNode* root) {
        if(!root) {
            return;
        }
        nodes.push_back(root);
        preorderTranverse(nodes, root->left);
        preorderTranverse(nodes, root->right);
    }
};

Reference

  1. https://leetcode.com/problems/flatten-binary-tree-to-linked-list/description/
相关标签: Leetcode