114. Flatten Binary Tree to Linked List
https://leetcode.com/problems/flatten-binary-tree-to-linked-list/description/
Thoughts
Code
/*
* @lc app=leetcode id=114 lang=cpp
*
* [114] Flatten Binary Tree to Linked List
*/
// @lc code=start
/**
* 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) {
stack<TreeNode*> s;
s.push(root);
TreeNode *last = nullptr;
while (!s.empty()) {
auto t = s.top(); s.pop();
if (t == nullptr) continue;
s.push(t->right);
s.push(t->left);
if (last != nullptr) {
last->left = nullptr;
last->right = t;
}
last = t;
}
}
};
// @lc code=end
Analysis
Ver.2
Last updated