zoukankan      html  css  js  c++  java
  • binary-tree-preorder-traversal

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

  • 相关阅读:
    HTML5---offline application(application cache)
    apache asp.net
    长轮询
    comet ajax轮询
    bootstrap3
    weixin
    backbone csdn
    backbone case
    backbone showcase
    javascript performance
  • 原文地址:https://www.cnblogs.com/cherrychenlee/p/10834302.html
Copyright © 2011-2022 走看看