题目描述:
题号:114
给你二叉树的根结点 root
,请你将它展开为一个单链表:
-
展开后的单链表应该同样使用
TreeNode
,其中right
子指针指向链表中下一个结点,而左子指针始终为null
。 -
展开后的单链表应该与二叉树 先序遍历 顺序相同。
解题思路:
思路一:前序遍历后构建链表
先前序遍历二叉树,再根据前序遍历的结果逐个节点构建链表
时间复杂度:O(N)
空间复杂度:O(N)
C++
// C++
/**
* 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) {
vector<TreeNode*> value;
stack<TreeNode*> sub;
TreeNode *node = root;
while(node != nullptr || sub.empty() == false) {
while(node != nullptr) {
value.push_back(node);
sub.push(node);
node = node->left;
}
node = sub.top();
sub.pop();
node = node->right;
}
int size = value.size();
for(int i = 1; i < size; i++) {
auto pre = value.at(i - 1);
auto cur = value.at(i);
pre->left = nullptr;
pre->right = cur;
}
}
};
go
// go
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func flatten(root *TreeNode) {
list := []*TreeNode{}
suBstack := []*TreeNode{}
node := root
for node != nil || len(suBstack) > 0 {
for node != nil {
list = append(list, node)
suBstack = append(suBstack, node)
node = node.Left
}
node = suBstack[len(suBstack)-1]
node = node.Right
suBstack = suBstack[:len(suBstack)-1]
}
for i := 1; i < len(list); i++ {
prev, curr := list[i-1], list[i]
prev.Left, prev.Right = nil, curr
}
}
标签:node,right,TreeNode,nullptr,suBstack,链表,二叉树,热题,left
From: https://blog.csdn.net/H_P10/article/details/142300758