zoukankan      html  css  js  c++  java
  • 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?

    Analyse: root, root->left, root->right

    1. Recursion

        Runtime: 0ms

     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> result;
    14         preorder(root, result);
    15         return result;
    16     }
    17     void preorder(TreeNode* root, vector<int>& result){
    18         if(root){
    19             result.push_back(root->val);
    20             preorder(root->left, result);
    21             preorder(root->right, result);
    22         }
    23         return ;
    24     }
    25 };

    2. Iteration  

      Runtime: 4ms

     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> result;
    14         stack<TreeNode*> stk;
    15         if(root) stk.push(root);
    16         else return result;
    17         
    18         while(!stk.empty()){
    19             TreeNode* temp = stk.top();
    20             result.push_back(temp->val);
    21             stk.pop();
    22             
    23             if(temp->right) stk.push(temp->right);
    24             if(temp->left) stk.push(temp->left);
    25         }
    26         return result;
    27     }
    28 };
  • 相关阅读:
    iOS开发之静态库(二)—— .a
    iOS开发之静态库(一)—— 基本概念
    Linux中ctrl-c, ctrl-z, ctrl-d 区别
    JNI技术基础(1)——从零开始编写JNI代码
    开篇纪念
    java面试题
    jvm系列二之GC收集器
    jvm系列一
    ConcurrentHashMap源码剖析(1.8版本)
    博客系统对比
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/4679784.html
Copyright © 2011-2022 走看看