LeetCode144—Binary Tree Preorder Traversal

布满荆棘的人生 2022-07-16 04:22 254阅读 0赞

原题

原题链接

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

For example:
Given binary tree {1,#,2,3},
1
\
2
/
3
return [1,2,3].

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

分析

很明显是考虑先序遍历的非递归写法,不过递归也能过。
参见:二叉树的遍历

  1. //递归
  2. class Solution {
  3. private:
  4. void preOrder(TreeNode*root,vector<int>&res)
  5. {
  6. if(root==NULL)
  7. return;
  8. res.push_back(root->val);
  9. preOrder(root->left,res);
  10. preOrder(root->right,res);
  11. }
  12. public:
  13. vector<int> preorderTraversal(TreeNode* root) {
  14. vector<int>res;
  15. preOrder(root,res);
  16. return res;
  17. }
  18. };
  19. //迭代
  20. class Solution {
  21. private:
  22. stack<TreeNode*>mystack;
  23. void preOrder(TreeNode*root,vector<int>&res)
  24. {
  25. TreeNode *p =root;
  26. while(p!=NULL||!mystack.empty())
  27. {
  28. while(p!=NULL)
  29. {
  30. res.push_back(p->val);
  31. mystack.push(p);
  32. p=p->left;
  33. }
  34. if(!mystack.empty())
  35. {
  36. p=mystack.top();
  37. mystack.pop();
  38. p=p->right;
  39. }
  40. }
  41. }
  42. public:
  43. vector<int> preorderTraversal(TreeNode* root) {
  44. vector<int>res;
  45. preOrder(root,res);
  46. return res;
  47. }
  48. };

发表评论

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

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

相关阅读