cherrychenlee

导航

 

原文地址: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

posted on 2019-05-08 20:09  cherrychenlee  阅读(75)  评论(0编辑  收藏  举报