Recursive implementation with stacks (traversal of binary tree)

Source: Internet
Author: User

First-order traversal

public void Getnodebystack (TreeNode node) {//Stack implementation first-order traversal
stack<treenode> stack = new stack<> ();
if (node==null) {
Return
}
Stack.push (node);
while (!stack.isempty ()) {
TreeNode TreeNode = Stack.pop ();
System.out.print (treenode.vl+ "");
if (treenode.right!=null) {
Stack.push (Treenode.right);
}
if (treenode.left!=null) {
Stack.push (Treenode.left);
}
}
}

Directly pull the top node out of the stack, then put the node into the stack, and then put the left node


Second, the middle sequence traversal

public void Getnodebystack (TreeNode node) {//stack implementation in sequence traversal
stack<treenode> stack = new stack<> ();
if (node==null) {
Return
}
Stack.push (node);
while (!stack.isempty ()) {
TreeNode TreeNode = Stack.pop ();
if (Treenode.flag) {
if (treenode.right!=null) {
Stack.push (Treenode.right);
}
Treenode.flag = false;
Stack.push (TreeNode);//node to go back to stack after decomposition
if (treenode.left!=null) {
Stack.push (Treenode.left);
}
}else{
System.out.print (treenode.vl+ "");
}
}
}

The difference between the sequence traversal and the first order is to have the sign bit flag, because the node's first stack is decomposed into the left and right nodes, the second is to traverse the output

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.