The first order, the middle order and the sequential traversal of the binary tree (recursive && non-recursive)

Source: Internet
Author: User

Tree node Definition:

class TreeNode {         int  val;         TreeNode left;         TreeNode right;         TreeNode (int  x) {          = x;          }     }

To build a two-fork tree recursively:

    //Recursive establishment of two-fork tree     Public Static voidBuildtree (TreeNode node,intdata) {        if(node = =NULL) {node=NewTreeNode (data); }                if(Data <=node.val) {            if(Node.left = =NULL) {Node.left=NewTreeNode (data); }Else{buildtree (node.left, data); }        }                if(Data >node.val) {            if(Node.right = =NULL) {Node.right=NewTreeNode (data); }Else{buildtree (node.right, data); }        }        }

1, First order traversal

Traverse mode: Root node---left node--right node

Recursive first-order traversal:

    // recursive traversal of binary tree    by First order  Public Static List<integer> Pretravese (TreeNode root,list<integer> arr) {        ifnull  )            return  arr;         if NULL ) {            arr.add (root.val);             = Pretravese (root.left,arr);             = Pretravese (root.right,arr);        }         return arr;    }

Non-recursive traversal:

For any one node P

1) Access the node p and put p into the stack.

2) Change p to the left child node of P, and if p is not empty, loop to 1); Otherwise pop up the current stack top using p to receive, will p into P's right child node;

3) ends the loop when the P node is null and the stack is empty.

Code:

    //non-recursive first-order traversal     Public StaticList<integer>preordertraversal (TreeNode root) {List<Integer> arr =NewArraylist<integer>(); if(Root = =NULL){            returnarr; } Stack<TreeNode> ts =NewStack<treenode>(); TreeNode ptr=Root;  while(PTR! =NULL|| !Ts.isempty ()) {             while(PTR! =NULL) {arr.add (ptr.val);                Ts.push (PTR); PTR=Ptr.left; }            if( !Ts.isempty ()) {ptr=Ts.pop (); PTR=Ptr.right; }        }        returnarr; }

2, Middle sequence traversal

Traversal: Left dial hand Tree------------right subtree

Recursive mid-order traversal:

    // middle order recursive traversal binary tree     Public Static List<integer> Intravese (TreeNode root,list<integer> arr) {        ifnull)             return arr;         if NULL ) {            = Intravese (root.left,arr);            Arr.add (root.val);             = Intravese (root.right,arr);        }         return arr;    }

Non-recursive in-sequence traversal:

For any one node P

1) When the node is not NULL, the node is pressed to stack;

2) Update p to its left child, if the left child is not empty, loop to 1), otherwise pop up the top element of the stack to p, Access p node, p update to the right child of P;

3) When P is null and the stack is empty, the loop ends.

Code:

    //in-sequence non-recursive traversal     Public StaticList<integer>inordertraversal (TreeNode root) {List<Integer> arr =NewArraylist<integer>(); if(Root = =NULL){            returnarr; } Stack<TreeNode> ts =NewStack<treenode>(); TreeNode ptr=Root;  while(PTR! =NULL|| !Ts.isempty ()) {             while(PTR! =NULL) {Ts.push (PTR); PTR=Ptr.left; }            if(!Ts.isempty ()) {ptr=Ts.pop ();                Arr.add (Ptr.val); PTR=Ptr.right; }        }        returnarr; }

3. Post-sequential traversal

Traversal mode: Left dial hand Tree----right subtree---root node

Recursive traversal:

    // Sequential recursive traversal of binary tree     Public Static List<integer> Lasttravese (TreeNode root,list<integer> arr) {        ifnull )            return  arr;         if NULL ) {            = Lasttravese (root.left,arr);             = Lasttravese (root.right,arr);            Arr.add (Root.val);        }         return arr;    }

Non-recursive traversal:

For any node p, put it into the stack, and then search along its left subtree until the node with no left child is found, at which point the node appears at the top of the stack, but it cannot be stacked and accessed at this time because its right child has not been accessed.

Next, follow the same rules to the right subtree to do the same processing, when the right child is finished, the node appears on the top of the stack, you can stack it and access it at this point.

This guarantees the correct order of access.

As you can see, in this process, each node appears at the top of the stack two times, and can only be accessed the second time it appears on top of the stack. Therefore, it is necessary to set more than one variable to identify whether the node appears first on the top of the stack.

Code:

First create a new class to record whether the node is the first stack:

// Create a new class to record if the node is not the first time the stack is played. class newtreenode{    TreeNode ptr;     Boolean IsFirst;      Public Newtreenode (TreeNode ptr) {        this. ptr = ptr;           This true ;    }}

Non-recursive sequential traversal of binary tree:

    //Sequential non-recursive traversal of binary tree     Public StaticList<integer>lasttraverse (TreeNode root) {List<Integer> arr =NewArraylist<integer>(); if(Root = =NULL){            returnarr; } Stack<NewTreeNode> nts =NewStack<newtreenode>(); Newtreenode nptr=NULL; TreeNode ptr=Root;  while(ptr!=NULL|| !Nts.isempty ()) {             while(PTR! =NULL) {nptr=NewNewtreenode (PTR);                Nts.push (NPTR); PTR=Ptr.left; }                        if(!Nts.isempty ()) {nptr=Nts.pop (); if(nptr.isfirst) {Nptr.isfirst=false;                    Nts.push (NPTR); PTR=Nptr.ptr.right; }Else{arr.add (nptr.ptr.val); //ptr is set to NULL because the left and right subtrees of it are now complete.PTR =NULL; }            }        }        returnarr; }}

The first order, the middle order and the sequential traversal of the binary tree (recursive && non-recursive)

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.