day 14 第六章二叉树
今日内容:
* 理论基础
*
递归遍历
*
迭代遍历
*
统一迭代
详细布置理论基础
需要了解 二叉树的种类,存储方式,遍历方式 以及二叉树的定义
文章讲解:https://programmercarl.com/%E4%BA%8C%E5%8F%89%E6%A0%91%E7%90%86%E8%AE%BA%E5%9F%BA%E7%A1%80.html递归遍历 (必须掌握)
二叉树的三种递归遍历掌握其规律后,其实很简单
题目链接/文章讲解/视频讲解:https://programmercarl.com/%E4%BA%8C%E5%8F%89%E6%A0%91%E7%9A%84%E9%80%92%E5%BD%92%E9%81%8D%E5%8E%86.html迭代遍历 (基础不好的录友,迭代法可以放过)
题目链接/文章讲解/视频讲解:https://programmercarl.com/%E4%BA%8C%E5%8F%89%E6%A0%91%E7%9A%84%E8%BF%AD%E4%BB%A3%E9%81%8D%E5%8E%86.html统一迭代 (基础不好的录友,迭代法可以放过)
这是统一迭代法的写法, 如果学有余力,可以掌握一下
题目链接/文章讲解:https://programmercarl.com/%E4%BA%8C%E5%8F%89%E6%A0%91%E7%9A%84%E7%BB%9F%E4%B8%80%E8%BF%AD%E4%BB%A3%E6%B3%95.html
/**
* 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:
#if 0
vector<int> preorderTraversal(TreeNode* root) {
vector<int> result;
preorder(root, result);
return result;
}
void preorder(TreeNode* root, vector<int> &result) {
if (root != nullptr) {
result.push_back(root->val);
preorder(root->left, result);
preorder(root->right, result);
}
}
#endif
#if 0
vector<int> preorderTraversal(TreeNode* root) {
vector<int> result;
if (root == nullptr) return result;
stack<TreeNode*> node_stack;
node_stack.push(root);
TreeNode* node;
while (!node_stack.empty()) {
node = node_stack.top();
node_stack.pop();
result.push_back(node->val);
if (node->right) node_stack.push(node->right);
if (node->left) node_stack.push(node->left);
}
return result;
}
#endif
vector<int> preorderTraversal(TreeNode* root) {
vector<int> result;
if (root == nullptr) return result;
stack<TreeNode*> node_stack;
TreeNode *node = root;
while (node != nullptr || !node_stack.empty()) {
if (node != nullptr) {
result.push_back(node->val);
node_stack.push(node);
node = node->left;
} else {
node = node_stack.top();
node_stack.pop();
node = node->right;
}
}
return result;
}
};