Binary Tree_ basic algorithm

/**

 * Definition for binary tree

 * struct TreeNode {

 *     int val;

 *     TreeNode *left;

 *     TreeNode *right;

 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}

 * };

 */

// 三种遍历的递归实现



void preOrder(TreeNode * root)

{

   if(NULL == root ) return ;

   visit(root->val);

   preOrder(root->left);

   preOrder(root->right);

}



void inOrder(TreeNode * root)

{

  if(NULL == root) return ;

  inOrder(root->left);

  visit(root->val);

  inOrder(root->right);

}



void postOrder(TreeNode * root)

{

  if(NULL == root) return ;

  postOrder(root->left);

  postOrder(root->right);

  visit(root->val);

}

 

// 三种遍历的非递归实现



void preOrder(TreeNode * root)

{

   if(NULL == root ) return ;

   std::stack<TreeNode *> myStack;

   TreeNode *p = root;



   while(p || !myStack.empty())

   {

        while(p){

            visit(p->val);

            if(p->right)

                 myStack.push(p->right);

            p = p->left;

        }

      

        if(!myStack.empty())

        {

          p = myStack.top();

          myStack.pop();

        }

   }

}



void inOrder(TreeNode * root)

{

  if(NULL == root) return ;

  std::stack<TreeNode *> myStack;

  TreeNode *p = root;

  

  while(p || !myStack.empty())

  {

    while(p)

    {

       myStack.push(p);

       p = p->left;

    }

    if(!myStack.empty())

    {

        p = myStack.top();

        myStack.pop();

        visit(p->val);

        p = p->right;

    }

  }

}



void postOrder(TreeNode * root)

{

  if(NULL == root) return ;

  std::stack<TreeNode *> myStack;

  TreeNode *p = root,*leftNode, *rightNode, *q;

  

  while(P || !myStack())

  {

        while(p){

             myStack.push(p); 

             leftNode = p->left;

             rightNode = p-> right;

             p = (leftNode) ? leftNode: rightNode ;

        }

        p = myStack.top();

        myStack.pop();

        visit(p->val);

        if( !myStack.empty() )

          {

             q = myStack.top();

             if(p == q->left) 

                 p = q->right;

          }else

                p = NULL:

  }

  

}
// 广度优先周游

void levelOrder(TreeNode * root)

{

   if(NULL == root ) return ;

   std::queue<TreeNode *> myQueue;

   TreeNode *p ;

   myQueue.push(root) ;



   while( !myQueue.empty())

   {

        p = myQueue.front();

        myQueue.pop();

        visit(p->val);

        if(p->left)

              myQueue.push(p->left);

        if(p->right)

              myQueue.push(p->right);

   }

}

 

你可能感兴趣的:(Algorithm)