Leetcode 114. Flatten Binary Tree to Linked List
程序员文章站
2022-03-04 19:05:10
...
文章作者:Tyan
博客:noahsnail.com | CSDN | 简书
1. Description
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
推荐阅读
-
LeetCode 114.Flatten Binary Tree to Linked List (二叉树展开为链表)
-
114. Flatten Binary Tree to Linked List(二叉树展开为链表)
-
Leetcode Flatten Binary Tree to Linked List
-
【leetcode】114. 二叉树展开为链表(Flatten Binary Tree to Linked List)(DFS)
-
Flatten Binary Tree to Linked List
-
【python/M/114】Flatten Binary Tree to Linked List
-
【LeetCode】convert-sorted-list-to-binary-search-tree
-
LeetCode: 114. Flatten Binary Tree to Linked List
-
114. Flatten Binary Tree to Linked List
-
LeetCode 114 Flatten Binary Tree to Linked List