zoukankan      html  css  js  c++  java
  • LeetCode:94. Binary Tree Inorder Traversal

    Given a binary tree, return the inorder traversal of its nodes' values.

    For example:
    Given binary tree [1,null,2,3],

       1
        
         2
        /
       3
    

    return [1,3,2].

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





    C++ Solution:

    /**
      * Definition for a binary tree node.
      * struct TreeNode {
      *     int val;
      *     TreeNode *left;
      *     TreeNode *right;
      *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
      * };
      */
    class Solution {
    public:
         vector<int> inorderTraversal(TreeNode* root) {
             vector<int> result;
            
             stack<TreeNode*> stack;

            TreeNode* curr = root;

            while (curr || !stack.empty()) {
                 while (curr) {
                     stack.push(curr);
                     curr = curr->left;
                 }

                curr = stack.top();
                 stack.pop();

                result.push_back(curr->val);

                curr = curr->right;
             }
             return result;
         }
        
         void traversal(TreeNode *root, vector<int> &list) {

            if (root != NULL) {
                 if (root->left != NULL)
                     traversal(root->left, list);

                list.push_back(root->val);

                if (root->right != NULL)
                     traversal(root->right, list);
             }
         }
    };

  • 相关阅读:
    route命令
    linux下限制ip访问
    linux安装oracle客户端
    Upgrading to Kentico 12
    online youtube subtitle downloader
    Driving continuous quality of your code with SonarCloud
    炉石传说 乱斗模式 三足鼎立
    Behavior-driven development
    TestNG like unit testing framework in C# (C sharp)
    Windows 10 & 8: Install Active Directory Users and Computers
  • 原文地址:https://www.cnblogs.com/ysmintor/p/7602533.html
Copyright © 2011-2022 走看看