zoukankan      html  css  js  c++  java
  • LeetCode-Binary Tree Preorder Traversal[二叉树]

     1 #include<iostream>
     2 #include<vector>
     3 #include<stack>
     4 using namespace std;
     5 
     6 class Solution
     7 {
     8 public:
     9     vector<int> preorderTraversal(TreeNode *root)
    10     {
    11         vector<int> result;
    12         const TreeNode *p;
    13         stack<const TreeNode *> s;
    14 
    15         p = root;
    16         if(p != nullptr)    s.push(p);
    17         while(!s.empty())
    18         {
    19             p = s.top();
    20             s.pop();
    21             result.push_back(p->val);
    22 
    23             if(p->right != nullptr)    s.push(p->right);
    24             if(p->left != nullptr)    s.push(p->left);    //stack 后进先出 所以先判断right
    25         }
    26         return result;
    27     }
    28 }
  • 相关阅读:
    git命令
    Linux基础知识手册
    Linux系统编程
    A
    Subsequences in Substrings Kattis
    G
    K
    K
    C
    E
  • 原文地址:https://www.cnblogs.com/yiruhua/p/5528407.html
Copyright © 2011-2022 走看看