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 }
  • 相关阅读:
    「codeforces
    「sdoi2019
    「ABC 218」解集
    「hdu
    「atcoder
    「tricks」平凡二分幻术
    并查集
    Bellman-Ford算法 & SPFA & SPFA_DFS
    最近公共祖先(LCA)
    题解 P5751 【[NOI1999]01串】
  • 原文地址:https://www.cnblogs.com/zhuangzebo/p/3991892.html
Copyright © 2011-2022 走看看