二叉树前序遍历

来源:互联网 发布:网络犯罪种类 编辑:程序博客网 时间:2024/06/06 03:40

前序遍历,就是 根-左-右 的顺序。

有递归和非递归的解法,递归还分遍历和分治两种解法,下面直接给出代码


递归遍历的解法,最直观的代码,这里需要辅助函数

vector<int> preorder(Tree* root) {vector<int> res;preoder_rec(root, res);  // 不需要判NULL,函数内部会处理return res;}void preorder_rec(Tree* root, vector<int>& res) {if (root == NULL) return;res.push_back(root->val);preorder_rec(root->left, res);  // 不需要判NULL,函数内部会处理preorder_rec(root->right, res); // 不需要判NULL,函数内部会处理}


递归分治的解法,就是分别算出左右子树的结果然后合并成总结果

vector<int> preorder(Tree* root) {vector<int> res;if (root == NULL) return res;vector<int> left = preorder(root->left);vector<int> right = preorder(root->right);res.push_back(root->val);res.insert(res.end(), left.begin(), left.end());res.insert(res.end(), right.begin(), right.end());return res;}


迭代的解法,需要使用一个栈进行辅助,先将root压栈

然后不断从栈顶取出元素,并将其值放入结果向量中,然后再将左右非空子节点逆序压入堆栈

不断循环,直到栈空

最后向量中就是所求结果

vector<int> preorder(Tree* root) {vector<int> res;if (root == NULL) return res;stack<Tree*> s;s.push(root);  //栈用的push,不是push_backwhile (!s.empty()) {Tree* node = s.top();s.pop();res.push_back(node->val);if (node->right) s.push(node->right); //注意压栈顺序是反的!非常容易出错!if (node->left) s.push(node->left);}return res;}



0 0