114 Flatten Binary Tree to Linked List
![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/f5ce2c82f062443d863fd0c13446cb02.png)
![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/ec06951fa809430c81ef717c318359d0.png)
class Solution {
public:
void flatten(TreeNode* root) {
if(!root) return;
stack<TreeNode*> curr;
if(root->right)curr.push(root->right);
if(root->left)curr.push(root->left);
TreeNode* write = root;
while(!curr.empty()){
TreeNode* read = curr.top();curr.pop();
write->right = read;
write->left = nullptr;
write = write->right;
if(read->right)curr.push(read->right);
if(read->left)curr.push(read->left);
}
}
};
c++代码review:先序遍历
void preorder(TreeNode* root){
if(!root) return;
stack<TreeNode*> stk;
while(!stk.empty()){
TreeNode* node = stk.top();stk.pop();
if(node->right) stk.push(node->right);
if(node->left)stk.push(node->left);
}
}
116 Populating Next Right Pointers in Each Node
![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/fbe587fc9fb2431d9f1a8027ab7cbb30.png)
![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/92d91cf886274f3f960e52e6afd8cba4.png)
class Solution {
public:
Node* connect(Node* root) {
if(!root) return root;
queue<Node*> que;
que.push(root);
Node* node = root;
while(!que.empty()){
int n = que.size();
for(int i = 0 ; i < n-1 ; i++){
node = que.front();
que.pop();
node->next = que.front();
if(node->left)que.push(node->left);
if(node->right)que.push(node->right);
}
node = que.front();
que.pop();
if(node->left)que.push(node->left);
if(node->right)que.push(node->right);
}
return root;
}
};
c++代码review:层次遍历
vector<vector<int>> levelorder(TreeNode* root){
if(!root) return {};
queue<TreeNode*> que;
que.push(root);
vector<vector<int>> res;
while(!que.empty()){
vector<int> prev = {};
int n = que.size();
for(int i = 0 ; i < n ;i ++){
TreeNode* node = que.front();
que.pop();
prev.push_back(node->val);
if(node->left)que.push(node->left);
if(node->right)que.push(node->right);
}
res.push_back(prev);
}
}