LeetCode 114 Flatten Binary Tree to Linked List
程序员文章站
2022-03-07 23:39:56
...
LeetCode 114
Flatten Binary Tree to Linked List
-
Problem Description:
将二叉树节点值用链表存储起来,根据题目给的例子可以看出实际考查的是树的先序遍历。
具体的题目信息:
https://leetcode.com/problems/flatten-binary-tree-to-linked-list/description/ - Example:
- 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 == NULL) return;
TreeNode* head = root;
TreeNode* p = root;
queue<TreeNode*> tree;
stack<TreeNode*> node;
while(p || !node.empty()) {
while(p) {
node.push(p);
tree.push(p);
p = p->left;
}
if (!node.empty()) {
p = node.top();
node.pop();
p = p->right;
}
}
p = head;
if (!tree.empty())
tree.pop();
while(!tree.empty()) {
TreeNode* q = new TreeNode(tree.front()->val);
tree.pop();
p->right = q;
p->left = NULL;
p = q;
}
p->right = NULL;
p->left = NULL;
root = head;
}
};
推荐阅读
-
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