[leetcode]binary-tree-preorder-Traversal

偏执的太偏执、 2022-03-20 05:50 248阅读 0赞

题目描述:

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

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

实现思路:

要实现非递归的二叉树前序遍历,可以借助栈来实现,前序遍历是根-左-右,先把根压栈然后弹出到vector中,再依次将右孩子压栈、左孩子压栈,然后迭代进行,每次都弹出栈底的结点~

具体实现:

  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> res;
  14. if(!root){
  15. return res;
  16. }
  17. stack<TreeNode *> st;
  18. st.push(root);
  19. while(st.size()){
  20. TreeNode * temp;
  21. temp = st.top();
  22. res.push_back(temp->val);
  23. st.pop();
  24. if(temp->right){
  25. st.push(temp->right);
  26. }
  27. if(temp->left){
  28. st.push(temp->left);
  29. }
  30. }
  31. return res;
  32. }
  33. };

发表评论

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

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

相关阅读