原文地址:https://www.jianshu.com/p/7592d4bd70cf

时间限制:1秒 空间限制:32768K

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?

我的代码

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> preorderTraversal(TreeNode *root) {
        vector<int> res;
        if(root==nullptr)
            return res;
        stack<TreeNode*> st;
        st.push(root);
        while(!st.empty()){
            TreeNode* cur=st.top();st.pop();
            res.push_back(cur->val);
            if(cur->right)
                st.push(cur->right);
            if(cur->left)
                st.push(cur->left);
        }
        return res;
    }
};

运行时间:3ms
占用内存:484k

相关文章:

  • 2021-12-22
  • 2022-01-30
  • 2021-10-25
  • 2022-01-22
  • 2021-11-05
  • 2022-02-26
猜你喜欢
  • 2021-09-04
  • 2021-05-11
  • 2022-02-03
  • 2021-05-24
相关资源
相似解决方案