zoukankan      html  css  js  c++  java
  • 【Leetcode】144. 二叉树的前序遍历

    144. 二叉树的前序遍历

    遍历方法:

    • 访问根结点;
    • 先序遍历其左子树;
    • 先序遍历其右子树

    解法1:

     1 /**
     2  * Definition for a binary tree node.
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
     8  *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
     9  *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
    10  * };
    11  */
    12 class Solution {
    13 public:
    14     vector<int> preorderTraversal(TreeNode* root) 
    15     {
    16         if(!root) return {};
    17         stack<TreeNode*> st;
    18         vector<int> res;
    19         st.push(root);
    20         
    21         while(!st.empty())
    22         {
    23             auto p = st.top();
    24             st.pop();
    25             res.push_back(p->val);
    26             if(p->right) st.push(p->right);
    27             if(p->left) st.push(p->left);
    28         }
    29         return res;
    30     }
    31 };
  • 相关阅读:
    FZU Monthly-201906 tutorial
    FZU Monthly-201906 获奖名单
    FZU Monthly-201905 tutorial
    BZOJ1009 GT考试
    BZOJ2428 均分数据
    模拟退火
    BZOJ3680 吊打XXX
    BZOJ4818 序列计数
    BZOJ4103 异或运算
    BZOJ3512 DZY Loves Math IV
  • 原文地址:https://www.cnblogs.com/sunbines/p/15535657.html
Copyright © 2011-2022 走看看