zoukankan      html  css  js  c++  java
  • leetcode

    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].

    思路:前序遍历,“根,左子树,右子树”

     1 #include <iostream>
     2 #include <vector>
     3 #include <stack>
     4 using namespace std;
     5 
     6 struct TreeNode {
     7     int val;
     8     TreeNode *left;
     9     TreeNode *right;
    10     TreeNode(int x): val(x), left(NULL), right(NULL) {}
    11 };
    12 
    13 class Solution {
    14 public:
    15     vector<int> preorderTraversal(TreeNode *root) {
    16         vector<int> res;
    17         stack<TreeNode*> s;
    18         if (!root) {
    19             return res;
    20         }
    21 
    22         s.push(root);
    23         while(!s.empty()) {
    24             TreeNode *p = s.top(); s.pop();
    25             res.push_back(p->val);
    26             if (p->right) {
    27                 s.push(p->right);
    28             }
    29             if (p->left) {
    30                 s.push(p->left);
    31             }
    32         }
    33         return res;    
    34     }
    35 };
    36 
    37 int main() {
    38     return 0;    
    39 }
  • 相关阅读:
    ssd的BUG
    ImportError: No module named lmdb
    GPU卡掉卡
    mobileeye
    caffe convert mxnet
    学前书单-百科
    捉襟见肘
    caffe+opencv3.3.1
    ipython notebook开通远程
    到底什么是故事点(Story Point)?
  • 原文地址:https://www.cnblogs.com/zhuangzebo/p/3991892.html
Copyright © 2011-2022 走看看