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;
        }
    };
  • 相关阅读:
    【读书笔记】MSDN 上关于加密解密的一个例子
    【读书笔记】创建泛型编程类 由链表而深入
    HDFS数据加密空间Encryption zone
    各种数据库的连接方法
    Java基础5
    Java基础4
    Java基础2
    博客优化、收录、RSS技巧
    Java基础3
    Java基础8
  • 原文地址:https://www.cnblogs.com/fightformylife/p/4244454.html
Copyright © 2011-2022 走看看