Recursive non-recursive recursion of binary tree traversal

Source: Internet
Author: User

Recursive

//Recursive first-order traversal     Public Static voidPre (TreeNode root) {if(root==NULL)return;        Visit (Root); if(root.left!=NULL) Pre (root.left); if(root.right!=NULL) Pre (root.right); }         //Recursive middle order traversal     Public Static voidIn (TreeNode root) {if(Root = =NULL)return; if(root.left!=NULL) in (Root.left);          Visit (Root); if(root.right!=NULL) in (root.right); }          //recursive post-sequential traversal     Public Static voidpost (TreeNode root) {if(Root = =NULL)return; if(root.left!=NULL) in (Root.left); if(root.right!=NULL) in (root.right);         Visit (Root); }

Non-recursive:

//non-recursive pre-sequence traversal--Stack     Public Static voidpretraverse (TreeNode root) {Stack<TreeNode> s=NewStack<treenode>();        S.push (root);  while(!S.isempty ()) {TreeNode current=S.pop ();            Visit (current); if(current.right!=NULL) S.push (current.right); if(current.left!=NULL) S.push (current.left); }            }    //non-recursive pre-sequence traversal--queue     Public Static voidpreTraverse2 (TreeNode root) {Queue<TreeNode> q=NewLinkedlist<treenode>();        Q.offer (root);  while(!Q.isempty ()) {TreeNode current=Q.poll ();            Visit (current); if(current.left!=NULL) Q.offer (current.left); if(current.right!=NULL) Q.offer (current.right); }            }    //non-recursive mid-order traversal     Public Static voidintraverse (TreeNode root) {Stack<TreeNode> s=NewStack<treenode>(); TreeNode T=Root;  while(!s.isempty () | | t!=NULL){            if(t!=NULL) {s.push (t); T=T.left; }Else{T=S.pop ();                Visit (t); T=T.right; }        }            }

Recursive non-recursive recursion of binary tree traversal

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.