---
title: "java 数据结构 二叉树"
author: "lemonhou"
date: "2014-07-21T19:42:03Z"
tags: []
categories: ["非技术"]
slug: "java"
draft: false
lastmod: "2014-07-21T19:42:03Z"
id: 2094656
url: "https://lemonhou.iteye.com/blog/2094656"
---

树是一种特殊的非线性的数据结构。二叉树是一种特殊的树，每个节点最多有两个孩子，称为“左孩子”和“右孩子”。
树结构的特点：它的每一个节点可以有不止一个的直接后继节点，除根以外每个节点都只有一个前驱结点。

链表是特殊的二叉树。

二叉树有两种特殊的形态;完全二叉树和满二叉树。

二叉树遍历

遍历是对树的一种最基本的运算，所谓遍历二叉树，就是按一定的规则和顺序走遍二叉树的所有结点，使每一个结点都被访问一次，而且只被访问一次。由于二叉树是非线性结构，因此，树的遍历实质上是将二叉树的各个结点转换成为一个线性序列来表示。

(1)先序遍历

首先访问根，再先序遍历左（右）子树，最后先序遍历右（左）子树。
(2)中序遍历

首先中序遍历左（右）子树，再访问根，最后中序遍历右（左）子树。
(3)后序遍历

首先后序遍历左（右）子树，再后序遍历右（左）子树，最后访问根。
（4）层次遍历

即按照层次访问，从左至右，从上到下。package hml.tree;



public class MainTree {
	public static void main(String args) {
		MainTree tree=new MainTree();
		TreeNode node=tree.creatTree(tree);
		tree.printTree(node);
		System.out.println("sss");
	}
	/*
	 * 创建二叉树
	 */
  public TreeNode creatTree(Object obj){
	  TreeNode root=new TreeNode("根");
	  TreeNode left=new TreeNode("左孩子");
	  TreeNode right=new TreeNode("右孩子");
	  root.leftchild=left;
	  root.rightchild=right;
	  left.parent=root;
	  right.parent=root;        
	  return root;
  }
  /*
   * 打印树
   */
  public  void printTree(TreeNode root){
	  if(root!=null){
		  System.out.println(root);
		  //获得左子节点
		  TreeNode left1=root.leftchild;
		  printTree(left1);
		  TreeNode right1=root.rightchild;
		  printTree(right1);
	  }
  }
}


package hml.tree;

public class TreeNode {
	Object obj;
	
	TreeNode  root;
	TreeNode  leftchild,rightchild;
	TreeNode  parent;
	public TreeNode(Object obj){
		this.obj=obj;
	}
   public String toString(){
	   
	return obj.toString();
   }
}