• binary-tree-preorder-traversal——前序遍历


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

    Note: Recursive solution is trivial, could you do it iteratively?

     1 /**
     2  * Definition for binary tree
     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         if(root==NULL)
    14             return v;
    15         v.push_back(root->val);
    16         preorderTraversal(root->left);
    17         preorderTraversal(root->right);
    18         return v;
    19     }
    20     vector<int> v;
    21 };

    非递归

     1 /**
     2  * Definition for binary tree
     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> v;
    14         if(root==NULL)
    15             return v;
    16         stack<TreeNode *> tree;
    17         tree.push(root);
    18         while(!tree.empty()){
    19             TreeNode *p=tree.top();
    20             v.push_back(p->val);
    21             tree.pop();
    22             if(p->right!=NULL)
    23                 tree.push(p->right);
    24             if(p->left!=NULL)
    25                 tree.push(p->left);
    26         }
    27         return v;
    28     }
    29 };
  • 相关阅读:
    NUnit
    Fxcop
    msdeploy命令实现远程部署时保留指定文件
    virtualBox 创建新虚拟机
    sharepoint项目部署
    执行批处理文件
    NCover
    配置Web DashBoard
    ccnet+ncover+fxcop+web deploy+mstest
    命令行部署Reporting Services项目
  • 原文地址:https://www.cnblogs.com/zl1991/p/6957988.html
Copyright © 2020-2023  润新知