二叉树的中序遍历 Binary Tree Inorder Traversal

方法:二叉树的先序遍历形式有递归和非递归两种。

递归方式的实现:

class Solution {
public:
    vector inorderTraversal(TreeNode *root) {
        vector out;
        fun(root, out);
        return out;
    }
    
    void fun(TreeNode *root, vector &out)
    {
        if(root != NULL)
        {
            fun(root->left, out);
            out.push_back(root->val);
            fun(root->right, out);
        }
    }
};
非递归方式的实现:

递归和栈总是对应的。二叉树的非递归中序遍历思想是,先让根结点进栈。然后把其左分支都进栈,直到左分支为空时才出栈,并让栈顶的右孩子入栈。

 class Solution {
public:
    stack s;
    
    vector inorderTraversal(TreeNode *root) {
        vector out;
        TreeNode *p = root;
        if(root==NULL)
            return out;
        do
        {
            while(p!=NULL)
            {
                s.push(p);
                p = p->left;
            }
            p = s.top();
            s.pop();
            out.push_back(p->val);
            p = p->right;
            if(p!=NULL)
            {
                s.push(p);
                p = p->left;
            }
        }while(!s.empty());
        
        return out;
    }
    
};

为二叉树的中序遍历操作设计一个迭代器

这样可以很方便的通过调用迭代器的接口来实现对二叉树结点的逐个遍历操作。

//设计一个虚基类,里面的这个next是纯虚函数。

class iterator{
     public:
          virtual Node* next() = 0;
};


//中序遍历迭代器类继承一下虚基类
class InorderIterator :public iterator {
     public:
          InorderIterator(Node* node)  //构造函数
          {
               Node *p = node;
               while(p != NULL)
               {
                    s.push(p);
                    p = p->left;
               }
          }

          virtual Node* next()  //迭代器接口
          {
               if(s.empty())
                    return NULL;
               Node *cur = s.top();
               s.pop();
               if(cur->right != NULL)
               {
                    Node*p = cur->right;
                    while(p != NULL)
                    {
                         s.push(p);
                         p = p->left;
                    }
               }
               return cur;
           }

     private:
          std::stack s;
};

使用这个迭代器

先要有个二叉树:Node *p = root;
定义并初始化迭代器:InorderIterator  it(p);
之后就可以使用它去遍历了,每调用一次next接口就返回下一个结点的地址:p = it->next(); (第一次调用next会返回中序遍历的第一个结点)


你可能感兴趣的:(树型结构问题,LeetCode,数据结构,我爱算法)