zoukankan      html  css  js  c++  java
  • Binary Tree Inorder Traversal

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

    For example:
    Given binary tree {1,#,2,3},

       1
        
         2
        /
       3
    

    return [1,3,2].

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

    中序遍历非递归版本

    法一:

    class Solution {
    private:
        vector<int> res;
    public:
        vector<int> inorderTraversal(TreeNode *root) {
            res.clear();
            if(root==NULL) return res;
            stack<pair<TreeNode*,bool>> s;
            s.push(make_pair(root,false));
            while (!s.empty())
            {
                root=s.top().first;
                while (root!=NULL&&!s.top().second)
                {
                    s.top().second=true;
                    root=root->left;
                    if(root!=NULL) s.push(make_pair(root,false));
                }
                root=s.top().first->right;
                res.push_back(s.top().first->val);
                s.pop();
                if(root!=NULL)
                    s.push(make_pair(root,false));
            }
            return res;
        }
    };

     

    法二:

    class Solution {
    private:
        vector<int> res;
    public:
        vector<int> inorderTraversal(TreeNode *root) {
            res.clear();
            if(root==NULL) return res;
            stack<pair<TreeNode*,bool>> s;
            TreeNode* t;
            int used;
            s.push(make_pair(root,false));
            while(!s.empty())
            {
                t=s.top().first;
                used = s.top().second;
                s.pop();
                if(!used)
                {
                    if(t->right!=NULL) s.push( make_pair(t->right,false));
                    s.push(make_pair(t,true));
                    if(t->left!=NULL) s.push( make_pair(t->left,false));
                }
                else res.push_back(t->val);
            }
            return res;
        }
    };
  • 相关阅读:
    613. Shortest Distance in a Line
    182. Duplicate Emails
    181. Employees Earning More Than Their Managers
    180. Consecutive Numbers
    612. Shortest Distance in a Plane
    178. Rank Scores
    177. Nth Highest Salary
    610. Triangle Judgement
    二维气泡弹窗
    jQuery触发a标签的click事件和原生javascript的区别
  • 原文地址:https://www.cnblogs.com/fightformylife/p/4244454.html
Copyright © 2011-2022 走看看