前序遍历即中左右
,前中后序遍历区别就在于中节点
是在前、中还是后。
利用栈实现二叉树的迭代遍历:
#include <stack>
#include <vector>
using std::stack;
using std::vector;
class Solution {
public:
vector<int> preorderTraversal(TreeNode *root) {
stack<TreeNode *> stk;
vector<int> res;
if (root == nullptr)
return res;
stk.push(root);
while (!stk.empty()) {
TreeNode *node = stk.top();
stk.pop();
res.push_back(node->val);
if (node->right != nullptr)
stk.push(node->right);
if (node->left != nullptr)
stk.push(node->left);
}
return res;
}
};
递归法:
class Solution {
public:
vector<int> res;
vector<int> preorderTraversal(TreeNode* root) {
if (root == nullptr)
return res;
res.push_back(root->val);
preorderTraversal(root->left);
preorderTraversal(root->right);
return res;
}
};
标签:node,binary,res,前序,stk,vector,二叉树,push,root
From: https://www.cnblogs.com/zwyyy456/p/16597805.html