Various traversal of algorithm binary tree

Source: Internet
Author: User

The traversal of the binary tree is basically the pre-sequence traversal, the middle sequence traversal, the post-order traversal and the hierarchical traversal. From the point of view of code, the first three simplest is recursive, the code is very concise. But recursion has a flaw, that is, when the nodes of the binary tree are very many, the recursion of the deep level will keep the stack and stack operation of the program, and the efficiency is lower. The recursive algorithm is not written here, only four kinds of ergodic non-recursive algorithms are written.

The nodes that define the binary tree first are as follows:

/**
* Definition for binary tree
* Public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode (int x) {val = x;}
* }
*/

The three kinds of non-recursive algorithms in the pre-order sequence can be realized by the stack, and the hierarchical traversal should be realized by the queue.

Pre-sequence traversal

Given a binary tree, return the preorder traversal of its nodes ' values.

For example:
Given binary Tree {1,#,2,3} ,

   1         2    /   3

Return [1,2,3] .


The first sequence traversal is the simplest of the four, that is, the root node is put into the stack, and then always out of the stack and keep the current node's right son and left son sequentially into the stack. Note that you must first right son after left son. Code as follows,

Public list<integer> preordertraversal (TreeNode root) {


List<integer> list=new arraylist<integer> ();
if (root==null)
{
return list;
}
Stack<treenode> stack=new stack<treenode> ();
Stack.push (root);
while (!stack.empty ())
{
TreeNode Node=stack.pop ();
List.add (Node.val);
if (node.right!=null)
{
Stack.push (Node.right);
}
if (node.left!=null)
{
Stack.push (Node.left);
}
}
return list;
}

Middle Sequence traversal

Given a binary tree, return the inorder traversal of its nodes ' values.

For example:
Given binary Tree {1,#,2,3} ,

   1         2    /   3

Return [1,3,2] .


First the root node into the stack, and then constantly find the current node's left son node, know that there is no left son, then the current node out of the stack, access, right son into the stack.

Public list<integer> inordertraversal (TreeNode root) {
List<integer> list=new arraylist<integer> ();
if (root==null)
{
return list;
}
Stack<treenode> stack=new stack<treenode> ();
Stack.push (root);
while (!stack.empty ())
{
TreeNode Node=null;
while ((Node=stack.peek ())!=null)
{
Stack.push (Node.left);

}
Stack.pop ();
if (!stack.empty ()) {
Node=stack.pop ();
List.add (Node.val);
Stack.push (Node.right);
}
}
return list;
}

Post-post traversal

Given a binary tree, return the postorder traversal of its nodes ' values.

For example:
Given binary Tree {1,#,2,3} ,

   1         2    /   3

Return [3,2,1] .

Post-order traversal complex, need to first access to the parent node, which need to record the last access node, if the current node's left and right son are empty, then the current node is a leaf node; If the previous node is the left son of the current node, the current node does not have a right son If the previous node is the right son of the current node, the descendants of the current node are already visited. In both cases, the current node is the next node to be accessed. The current node is accessed from the stack. If this is not the case, then the right son and the left son are put into the stack in turn.

Public list<integer> postordertraversal (TreeNode root) {

List<integer> list=new arraylist<integer> ();
if (root==null)
{
return list;
}
TreeNode Pre=null;
Stack<treenode> stack=new stack<treenode> ();
Stack.push (root);
while (!stack.empty ())
{
TreeNode Node=stack.peek ();
if ((node.left==null&&node.right==null) | | | (pre!=null&& (pre==node.left| | Pre==node.right)))
{
List.add (Node.val);
Pre=node;
Stack.pop ();
}
Else
{
if (node.right!=null)
{
Stack.push (Node.right);
}
if (node.left!=null)
{
Stack.push (Node.left);
}
}



}
return list;
}

Hierarchical traversal

Given a binary tree, return the level order traversal of its nodes ' values. (ie, from left-to-right, level by level).

For example:
Given binary Tree {3,9,20,#,#,15,7} ,

    3   /   9    /   7

Return its level order traversal as:

[  3],  [9,20],  [15,7]]
Hierarchy traversal requires the use of the queue structure, the queue is to the structure of the FIFO, and the hierarchical traversal of the book exactly the same.

The description of the subject is more complex than the normal traversal, not only the hierarchy traversal, but also a single list for each layer. This defines a variable count, with an initial value of 1, representing the number of nodes in the current hierarchy. This way, as long as you iterate through the count nodes, the nodes that represent the current level are all accessed.

Public list<list<integer>> Levelorder (TreeNode root) {
List<list<integer>> result=new arraylist<list<integer>> ();
Linkedlist<treenode> queue=new linkedlist<treenode> ();
if (root==null)
{
return result;
}
int count=0;
Queue.add (root);
Count=1;
while (Queue.size ()!=0)
{
int temp=0;
List<integer> list=new arraylist<integer> ();
for (int i=0;i<count;i++)
{
TreeNode Node=queue.poll ();

if (node!=null)
{
List.add (Node.val);
if (node.left!=null)
{
Queue.add (Node.left);
temp++;
}
if (node.right!=null)
{
Queue.add (Node.right);
temp++;
}
}

}
Result.add (list);
Count=temp;
}
return result;


}


All of the above code is tested and passed in Leetcode.

Various traversal of the algorithm binary 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.