zoukankan      html  css  js  c++  java
  • Binary Tree Preorder Traversal

     1 /**
     2  * Definition for a binary tree node.
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8  * };
     9  */
    10 class Solution {
    11 public:
    12     vector<int> preorderTraversal(TreeNode* root) {
    13                vector<int> res;
    14                if(root == NULL)
    15                       return res;
    16                stack<TreeNode*> node;
    17                node.push(root);
    18                TreeNode *p, *cur;
    19                p = root;
    20                res.push_back(p->val);
    21                while(!node.empty())
    22                {
    23                       while(p->left != NULL)
    24                       {
    25                             p = p->left;
    26                             res.push_back(p->val);
    27                             node.push(p);
    28                       }
    29                       cur = node.top();
    30                       node.pop();
    31                       if(cur->right != NULL)
    32                       {
    33                             p = cur->right;
    34                             res.push_back(p->val);
    35                             node.push(p);
    36                       }
    37                }
    38                return res;
    39     }
    40 };
  • 相关阅读:
    iOS基础
    iOS基础 ----- 内存管理
    NSAttributedString 的一些基本用法
    node安装使用
    docker常用命令
    docker lnmp
    easy-wechat
    composer
    center7系统搭建lnmp
    xammp环境配置
  • 原文地址:https://www.cnblogs.com/daocaorenblog/p/5519032.html
Copyright © 2011-2022 走看看