二叉树先序遍历

爱被打了一巴掌 2022-05-16 12:52 291阅读 0赞

下面是leetcode上的一道题,先序遍历二叉树。

Given a binary tree, return the preorder traversal of its nodes’ values.

For example:
Given binary tree{1,#,2,3},

  1. 1
  2. \
  3. 2
  4. /
  5. 3

return[1,2,3].

Note: Recursive solution is trivial, could you do it iteratively?

对于二叉树的遍历,很容易联想到递归,那么第一种思路就是使用递归的思想,参考代码如下:

  1. /**
  2. * Definition for binary tree
  3. * struct TreeNode {
  4. * int val;
  5. * TreeNode *left;
  6. * TreeNode *right;
  7. * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
  8. * };
  9. */
  10. class Solution {
  11. public:
  12. vector<int> preorderTraversal(TreeNode *root) {
  13. vector<int> result;
  14. helper(root,result);
  15. return result;
  16. }
  17. void helper(TreeNode *node,vector<int> &result){
  18. if (node==NULL){
  19. return;
  20. }
  21. result.push_back(node->val);
  22. helper(node->left,result);
  23. helper(node->right,result);
  24. }
  25. };

我们再司考一下,先序遍历就是根节点、左子节点、右子节点,那么也可以通过ADT栈来实现。

  1. class Solution {
  2. public:
  3. vector<int> preorderTraversal(TreeNode *root) {
  4. vector<int> res;
  5. stack<TreeNode *> s;
  6. if (root == NULL){
  7. return res;
  8. }
  9. s.push(root);
  10. while (!s.empty()){
  11. TreeNode *cur = s.top();
  12. s.pop();
  13. res.push_back(cur->val);
  14. if (cur->right!=NULL)
  15. s.push(cur->right);
  16. if (cur->left!=NULL)
  17. s.push(cur->left);
  18. }
  19. return res;
  20. }
  21. };

发表评论

表情:
评论列表 (有 0 条评论,291人围观)

还没有评论,来说两句吧...

相关阅读

    相关

    前两天面试,看见了个笔试题,关于二叉树的,今天算是把自己的一点理解写下来吧。 今天看网文,才想起来,二叉树的先序遍历、中序遍历、后序遍历, 遍历顺序都是

    相关

      二叉树不同于列表、链表、栈、队列这些线性结构,也不同于图这种非线性结构,它属于半线性结构。我们在搞二叉树的时候不要从轮子造起,而要善于引用此前的工作成果,转化成以前已经玩烂