Using recursive and non-recursive methods to realize the first order, the middle order and the sequential traversal of two-fork tree

Source: Internet
Author: User

A long time did not write a blog, but also for a long time did not calm down to learn technology, specific reasons no longer more tangled.

Recently completed the 0-ding task to brush the Leetcode every day, read the book (such as this record is the Zhoecheng of the "Programmer Code Interview Guide" content)

Review and learn some algorithms and related knowledge to consolidate the foundation.

Most of the algorithm's program code is not written by its first AC, because when flipping through books and appreciating the code of the discuss area gangster with a 100% beat rate,

Often find a more concise and beautiful wording, and sometimes even find some "shock for the Human" operation (base, not 6).

The content may be repeated with the previous write, the same as the Java implementation, and then some expansion.

Well, that's the end of the slag-forcing.

Tree structure definition

     Public class TreeNode {        publicint  val;          Public TreeNode left;          Public TreeNode right;          Public TreeNode (int  x) {            this. val = x;        }    } 

The first order, the middle order, the sequence refers to the root node, the first order: root around; preface: Zogen right;

The difference between recursion is as follows: The position of the output statement is adjusted.

     Public voidpreorderrecur (TreeNode root) {if(Root = =NULL)            return;        System.out.println (Root.val);        Preorderrecur (Root.left);    Preorderrecur (Root.right); }     Public voidinorderrecur (TreeNode root) {if(Root = =NULL)            return;        Inorderrecur (Root.left);        System.out.println (Root.val);    Inorderrecur (Root.right); }     Public voidposorderrecur (TreeNode root) {if(Root = =NULL)            return;        Posorderrecur (Root.left);        Posorderrecur (Root.right);    System.out.println (Root.val); }
View Code

The problem solved by recursive method can be realized by non-recursive method. Because the recursive method uses the function stack to save the information, the same function can be achieved if the data structure of the application is used instead of the function stack.

Non-recursive first-order traversal:

1, the application stack, the head node into the stack;

2, pop up the stack top and print, right child into the stack (not null), left child into the stack (not null);

3. Repeat step 2 until the stack is empty.

     Public voidpreorderunrecur (TreeNode root) {if(Root = =NULL)            return; Stack<TreeNode> s =NewStack<treenode>();        S.push (root);  while(!S.isempty ()) {Root=S.pop ();            System.out.println (Root.val); if(Root.right! =NULL) S.push (root.right); if(Root.left! =NULL) S.push (root.left); }    }

Non-recursive in-sequence traversal:

1, application stack, make cur=root;

2, cur into the stack, constantly make cur=cur.left into the stack;

3, Cur==null, a node is popped from the stack and printed, so cur=node.right, repeat step 2;

4, repeat 2, 3 until the stack empty and cur empty.

     Public voidinorderunrecur (TreeNode root) {if(Root = =NULL)            return; Stack<TreeNode> s =NewStack<treenode>();  while(!s.isempty () | | \ root! =NULL) {            if(Root! =NULL) {s.push (root); Root=Root.left; } Else{root=S.pop ();                System.out.println (Root.val); Root=Root.right; }        }    }

Non-recursive post-traversal:

The first is the implementation of two stacks, a better understanding:

1, the application stack S1,s2, head node into the S1;

2, S1 in the pop-up node recorded as Cur,cur press into the s2,cur left and right children pressed into S1;

3, repeat 2 until the S1 is empty;

4, from the S2 constantly out of the stack and print.

Explanation: The head node of each subtree was first popped from S1, then the child of that node was pressed into the S1 in the order of first left and right.

Then the order from the S1 is the first right again left, the total order is right and left, then the order from the S2 is the left (inverse s1).

    //Stacks     Public voidposOrderUnRecur1 (TreeNode root) {if(Root = =NULL)            return; Stack<TreeNode> S1 =NewStack<treenode>(); Stack<TreeNode> s2 =NewStack<treenode>();        S1.push (root);  while(!S1.isempty ()) {            //the head node of each subtree is first popped out of the S1.Root =S1.pop ();            S2.push (root); //first left and right press, the total out of the stack order for the right and left, then S2 out the stack order is about            if(Root.left! =NULL) S1.push (root.left); if(Root.right! =NULL) S1.push (root.right); }         while(!S2.isempty ())    System.out.println (S2.pop (). val); }

Then is the implementation of a stack:

1, the application stack, the head node into the stack, set the variable h and C,h represents the most recent pop-up and printing node, c for the top node of the stack, the first time H is the head node, c is null;

2, make C=stack.peek (); Even if C equals the top node of the stack, but the top of the stack does not eject, in three cases:

Ⅰ if c.left = null, and H! = C.left, and h!=c.right, then C's left child into the stack.

Explanation: H represents the most recently ejected and printed node, if H==c.left or h==c.right, stating that C's Saozi right subtree has been printed,

The left child of C should not be put into the stack again. Otherwise, the Zuozi of C has not been processed, then C's left child into the stack.

Ⅱ If the condition Ⅰ is not true and c.right! = is null, and H! = C.right, then C's right child is in the stack.

Ⅲ if Ⅰ and Ⅱ are not established, the C Saozi right subtree is printed, then pop C from the stack and print, so h=c.

3. Repeat step 2 until the stack is empty.

    //h represents the last node that was ejected and printed, and C represents the stack top node of the stack//at first, H is the head node and C is null     Public voidposOrderUnRecur2 (TreeNode h) {if(H = =NULL)            return; Stack<TreeNode> s =NewStack<treenode>();        S.push (h); TreeNode C=NULL;  while(!S.isempty ()) {C=S.peek (); if(C.left! =NULL&& h! = C.left && h! =c.right) S.push (c.left); Else if(C.right! =NULL&& h! =c.right) S.push (c.right); Else{System.out.println (S.pop (). val); H=C; }        }    }

Using recursive and non-recursive methods to realize the first order, the middle order and the sequential traversal of two-fork tree

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.