码迷,mamicode.com
首页 > 其他好文 > 详细

Tree traversal algorithms

时间:2015-06-27 11:21:16      阅读:94      评论:0      收藏:0      [点我收藏+]

标签:

You are encouraged tosolve this taskaccording to the task description, using any language you may know.

Implement a binary tree where each node carries an integer, and implement preoder, inorder, postorder and level-order traversal. Use those traversals to output the following tree:

         1
        /        /         /          2       3
    / \     /
   4   5   6
  /       /  7       8   9

The correct output should look like this:

preorder:    1 2 4 7 5 3 6 8 9
inorder:     7 4 2 5 1 8 6 9 3
postorder:   7 4 5 2 8 9 6 3 1
level-order: 1 2 3 4 5 6 7 8 9

package com.hephec.test; import java.util.LinkedList; import java.util.Queue; public class TreeTraverse { private static class Node<T>{ public Node<T> left; public Node(T data) { super(); this.data = data; } public Node<T> getLeft() { return left; } public void setLeft(Node<T> left) { this.left = left; } public Node<T> getRight() { return right; } public void setRight(Node<T> right) { this.right = right; } public T getData() { return data; } public void setData(T data) { this.data = data; } public Node<T> right; public T data; } //preorder traverse public static void preorder(Node<?> n){ if(n!=null){ System.out.println(n.data+" "); preorder(n.getLeft()); preorder(n.getRight()); } } //inorder traverse public static void inorder(Node<?> n){ if(n!=null){ inorder(n.getLeft()); System.out.println(n.data+" "); inorder(n.getRight()); } } //postorder traverse public static void postorder(Node<?> n){ if(n!=null){ postorder(n.getLeft()); postorder(n.getRight()); System.out.println(n.getData()); } } //level traverse public static void levelorder(Node<?> n){ Queue<Node<?>> nodequeue=new LinkedList<Node<?>>(); if(n!=null){ nodequeue.add(n); } while(!nodequeue.isEmpty()){ Node<?> next=nodequeue.remove(); System.out.println(next.data+" "); if(next.getLeft()!=null){ nodequeue.add(next.getLeft()); } if(next.getRight()!=null){ nodequeue.add(next.getRight()); } } } public static void main(String[] args) { Node<Integer> one = new Node<Integer>(1); Node<Integer> two = new Node<Integer>(2); Node<Integer> three = new Node<Integer>(3); Node<Integer> four = new Node<Integer>(4); Node<Integer> five = new Node<Integer>(5); Node<Integer> six = new Node<Integer>(6); Node<Integer> seven = new Node<Integer>(7); Node<Integer> eight = new Node<Integer>(8); Node<Integer> nine = new Node<Integer>(9); one.setLeft(two); one.setRight(three); two.setLeft(four); two.setRight(five); three.setLeft(six); four.setLeft(seven); six.setLeft(eight); six.setRight(nine); preorder(one); System.out.println(); inorder(one); System.out.println(); postorder(one); System.out.println(); levelorder(one); System.out.println(); } }

  

Tree traversal algorithms

标签:

原文地址:http://www.cnblogs.com/hephec/p/4603705.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!