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

    思路:用栈。之间复杂度O(n),空间复杂度O(n)

      

     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*> s;
    15         TreeNode *p = root;
    16         
    17         while (p != NULL || !s.empty()) {
    18             if (p != NULL) {
    19                 result.push_back(p->val);
    20                 s.push(p);
    21                 p = p->left;
    22             } else {
    23                 p = s.top();
    24                 s.pop();
    25                 p = p->right;
    26             }
    27         }
    28          return result;
    29     }
    30 };
  • 相关阅读:
    17.CSS 文本属性和字体属性
    15.CSS 浮动
    D. Same GCDs
    B. Infinite Prefixes
    D. 0-1 MST
    lambda表达式复习
    D. New Year and Conference
    C. New Year and Permutation
    D. Dr. Evil Underscores
    D. Minimax Problem
  • 原文地址:https://www.cnblogs.com/vincently/p/4229654.html
Copyright © 2011-2022 走看看