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);
             }
         }
    };

  • 相关阅读:
    topcoder srm 640 div1
    具体数学第二版第四章习题(5)
    topcoder srm 635 div1
    topcoder srm 630 div1 (2-SAT and SCC template)
    具体数学第二版第四章习题(4)
    topcoder srm 625 div1
    具体数学第二版第四章习题(3)
    具体数学第二版第四章习题(2)
    topcoder srm 615 div1
    具体数学第二版第四章习题(1)
  • 原文地址:https://www.cnblogs.com/ysmintor/p/7602533.html
Copyright © 2011-2022 走看看