zoukankan      html  css  js  c++  java
  • leetcode[144]Binary Tree Preorder Traversal

    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==NULL)return res;
            stack<TreeNode *> sta;
            sta.push(root);
            while(!sta.empty())
            {
                TreeNode *tmp=sta.top();
                sta.pop();
                res.push_back(tmp->val);
                if(tmp->right)sta.push(tmp->right);
                if(tmp->left)sta.push(tmp->left);
            }
            return res;
        }
    /**
    void preorder(vector<int> &res, TreeNode * root)
    {
        if(root==NULL)return;
        res.push_back(root->val);
        preorder(res,root->left);
        preorder(res,root->right);
    }
        vector<int> preorderTraversal(TreeNode *root) {
            vector<int> res;
            preorder(res,root);
            return res;
        }
    */
    };
  • 相关阅读:
    将Excel文件.xls导入SQL Server 2005
    linux mount命令
    python write file
    vim visual模式 复制
    chef简介
    录音整理文字工具otranscribe简介
    ftp put get 的使用方法
    yum lock 解决方法
    phalcon builder get raw sql
    centos7安装VirtualBox
  • 原文地址:https://www.cnblogs.com/Vae1990Silence/p/4281221.html
Copyright © 2011-2022 走看看