java建立樹
㈠ 找一個java程序:關於二叉樹的建立和排序
從鍵盤接受輸入(先序),以二叉鏈表作為存儲結構,建立二叉樹(以先序來建立)
結果不是唯一
㈡ java中如何建立一個java樹,請詳解
importjava.awt.*;
importjavax.swing.*;
classTreeDemoextendsJFrame
{
publicTreeDemo()
{
setSize(400,300);
setTitle("演示怎樣使用JTree");
show();
JScrollPanejPanel=newJScrollPane();
getContentPane().add(jPanel);
JTreejtree=newJTree();
jPanel.getViewport().add(jtree,null);
validate();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
publicclassExample5_25
{
publicstaticvoidmain(String[]args)
{
TreeDemoframe=newTreeDemo();
}
}
其中JScrollPane是一個帶滾動條的面板類。
將對象加入到帶滾動條的面板類中,在將已建的數放入到其中。
就可建立一個系統默認的樹結構。
㈢ 如何用Java實現樹形結構啊
定義一個簡單的菜單類 這里是簡單的示例 你可以自行擴展package entity;import java.util.ArrayList;
import java.util.List;/**
 * 菜單類
 * @author Administrator
 *
 */
public class Menu {
 /**
  * 菜單標題
  */
 private String title;
 /**
  * 子菜單的集合
  */
 private List<Menu> childs;
 
 /**
  * 父菜單
  */
 private Menu parent;
 
 /**
  * 構造函數 初始化標題和子菜單集合
  */
 public Menu(String title) {
  this();
  this.title=title;
 }
 /**
  * 構造函數 創建一個虛擬的父菜單(零級菜單) 所有的一級菜單都歸屬於一個虛擬的零級菜單
  *
  */
 public Menu() {
  this.childs = new ArrayList<Menu>();
 }
 /**
  * 獲取子菜單
  * @return
  */
 public List<Menu> getChilds() {
  return childs;
 }
 /**
  * 獲取標題
  * @return
  */
 public String getTitle() {
  return title;
 }
 /**
  * 獲取父菜單
  * @return
  */
 public Menu getParent() {
  return parent;
 }
 /**
  * 添加子菜單並返回該子菜單對象
  * @param child
  * @return
  */
 public Menu addChild(Menu child){
  this.childs.add(child);
  return child;
 }
 /**
  * 設置父菜單
  * @param parent
  */
 public void setParent(Menu parent) {
  this.parent = parent;
 }
 /**
  * 設置標題
  * @param title
  */
 public void setTitle(String title) {
  this.title = title;
 }
} 測試package entity;
/**
 * 測試類
 * @author Administrator
 *
 */
public class Test { /**
  * @param args
  */
 public static void main(String[] args) {
  /**
   * 創建一個虛擬的父菜單 用於存放一級菜單 menu01 和 menu02
   */
  Menu root = new Menu();
  /**
   * 創建兩個一級菜單
   */
  Menu menu01 = new Menu("一級菜單01");
  Menu menu02 = new Menu("一級菜單02");
  /**
   * 加入虛擬菜單
   */
  root.addChild(menu01);
  root.addChild(menu02);
  /**
   * 為兩個一級菜單分別添加兩個子菜單 並返回該子菜單 需要進一步處理的時候 才接收返回的對象 否則只要調用方法
   */
  Menu menu0101 = menu01.addChild(new Menu("二級菜單0101"));
  menu01.addChild(new Menu("二級菜單0102"));
  menu02.addChild(new Menu("二級菜單0201"));
  Menu menu0202 = menu02.addChild(new Menu("二級菜單0202"));
  /**
   * 添加三級菜單
   */
  menu0101.addChild(new Menu("三級菜單010101"));
  menu0202.addChild(new Menu("三級菜單020201"));
  /**
   * 列印樹形結構
   */
  showMenu(root);
 } /**
  * 遞歸遍歷某個菜單下的菜單樹
  * 
  * @param menu
  *            根菜單
  */
 private static void showMenu(Menu menu) {
  for (Menu child : menu.getChilds()) {
   showMenu(child, 0);
  }
 } private static void showMenu(Menu menu, int tabNum) {
  for (int i = 0; i < tabNum; i++)
   System.out.print("\t");
  System.out.println(menu.getTitle());
  for (Menu child : menu.getChilds())
   // 遞歸調用
   showMenu(child, tabNum + 1);
 }}
控制台輸出結果 一級菜單01        二級菜單0101
                三級菜單010101
        二級菜單0102一級菜單02
        二級菜單0201
        二級菜單0202
                三級菜單020201
㈣ 用java怎麼構造一個二叉樹呢
二叉樹的相關操作,包括創建,中序、先序、後序(遞歸和非遞歸),其中重點的是java在先序創建二叉樹和後序非遞歸遍歷的的實現。
package com.algorithm.tree;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Queue;
import java.util.Scanner;
import java.util.Stack;
import java.util.concurrent.LinkedBlockingQueue;
public class Tree<T> {
	private Node<T> root;
	
	public Tree() {
	}
	
	public Tree(Node<T> root) {
		this.root = root;
	}
	
	//創建二叉樹
	public void buildTree() {
		
		Scanner scn = null;
		try {
			scn = new Scanner(new File("input.txt"));
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		root = createTree(root,scn);		
	}
	//先序遍歷創建二叉樹
	private Node<T> createTree(Node<T> node,Scanner scn) {
		
		String temp  = scn.next();
		
		if (temp.trim().equals("#")) {
			return null;
		} else {
			node = new Node<T>((T)temp);
			node.setLeft(createTree(node.getLeft(), scn));
			node.setRight(createTree(node.getRight(), scn));
			return node;
		}
			
	}
//中序遍歷(遞歸)
	public void inOrderTraverse() {
		inOrderTraverse(root);
	}
	
	public void inOrderTraverse(Node<T> node) {
		if (node != null) {
			inOrderTraverse(node.getLeft());
			System.out.println(node.getValue());
			inOrderTraverse(node.getRight());
		}
	}
//中序遍歷(非遞歸)
	public void nrInOrderTraverse() {
		
		Stack<Node<T>> stack = new Stack<Node<T>>();
		Node<T> node = root;
		while (node != null || !stack.isEmpty()) {
			while (node != null) {
				stack.push(node);
				node = node.getLeft();
			}
			node = stack.pop();
			System.out.println(node.getValue());
			node = node.getRight();
			
		}
				
	}
	//先序遍歷(遞歸)
	public void preOrderTraverse() {
		preOrderTraverse(root);
	}
	
	public void preOrderTraverse(Node<T> node) {
		if (node != null) {
			System.out.println(node.getValue());
			preOrderTraverse(node.getLeft());
			preOrderTraverse(node.getRight());
		}
	}
//先序遍歷(非遞歸)
	public void nrPreOrderTraverse() {
		
		Stack<Node<T>> stack = new Stack<Node<T>>();
		Node<T> node = root;
		
		while (node != null || !stack.isEmpty()) {
			
			while (node != null) {
				System.out.println(node.getValue());
				stack.push(node);
				node = node.getLeft();
			}
			node = stack.pop();
			node = node.getRight();
		}
				
	}
	
	//後序遍歷(遞歸)
	public void postOrderTraverse() {
		postOrderTraverse(root);
	}
	
	public void postOrderTraverse(Node<T> node) {
		if (node != null) {
			postOrderTraverse(node.getLeft());
			postOrderTraverse(node.getRight());
			System.out.println(node.getValue());
		}
	}
	
	//後續遍歷(非遞歸)
	public void nrPostOrderTraverse() {
		
		Stack<Node<T>> stack = new Stack<Node<T>>();
		Node<T> node = root;
		Node<T> preNode = null;//表示最近一次訪問的節點
		
		while (node != null || !stack.isEmpty()) {
			
			while (node != null) {
				stack.push(node);
				node = node.getLeft();
			}
			
			node = stack.peek();
			
			if (node.getRight() == null || node.getRight() == preNode) {
				System.out.println(node.getValue());
				node = stack.pop();
				preNode = node;
				node = null;
			} else {
				node = node.getRight();
			}
			
		}
}
	
	//按層次遍歷
	public void levelTraverse() {
		levelTraverse(root);
	}
	
	public void levelTraverse(Node<T> node) {
	
		Queue<Node<T>> queue = new LinkedBlockingQueue<Node<T>>();
		queue.add(node);
		while (!queue.isEmpty()) {
			
			Node<T> temp = queue.poll();
			if (temp != null) {
				System.out.println(temp.getValue());
				queue.add(temp.getLeft());
				queue.add(temp.getRight());
			}
						
		}
				
	}
}
//樹的節點
class Node<T> {
	
	private Node<T> left;
	private Node<T> right;
	private T value;
	
	public Node() {
	}
	public Node(Node<T> left,Node<T> right,T value) {
		this.left = left;
		this.right = right;
		this.value = value;
	}
	
	public Node(T value) {
		this(null,null,value);
	}
	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 getValue() {
		return value;
	}
	public void setValue(T value) {
		this.value = value;
	}
		
}
測試代碼:
package com.algorithm.tree;
public class TreeTest {
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Tree<Integer> tree = new Tree<Integer>();
		tree.buildTree();
		System.out.println("中序遍歷");
		tree.inOrderTraverse();
		tree.nrInOrderTraverse();
		System.out.println("後續遍歷");
		//tree.nrPostOrderTraverse();
		tree.postOrderTraverse();
		tree.nrPostOrderTraverse();
		System.out.println("先序遍歷");
		tree.preOrderTraverse();
		tree.nrPreOrderTraverse();
		
//
	}
}
㈤ 用java怎麼構造一個二叉樹
二叉樹的相關操作,包括創建,中序、先序、後序(遞歸和非遞歸),其中重點的是java在先序創建二叉樹和後序非遞歸遍歷的的實現。
package com.algorithm.tree;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Queue;
import java.util.Scanner;
import java.util.Stack;
import java.util.concurrent.LinkedBlockingQueue;
public class Tree {
	private Node root;
	
	public Tree() {
	}
	
	public Tree(Node root) {
		this.root = root;
	}
	
	//創建二叉樹
	public void buildTree() {
		
		Scanner scn = null;
		try {
			scn = new Scanner(new File("input.txt"));
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		root = createTree(root,scn);		
	}
	//先序遍歷創建二叉樹
	private Node createTree(Node node,Scanner scn) {
		
		String temp  = scn.next();
		
		if (temp.trim().equals("#")) {
			return null;
		} else {
			node = new Node((T)temp);
			node.setLeft(createTree(node.getLeft(), scn));
			node.setRight(createTree(node.getRight(), scn));
			return node;
		}
			
	}
//中序遍歷(遞歸)
	public void inOrderTraverse() {
		inOrderTraverse(root);
	}
	
	public void inOrderTraverse(Node node) {
		if (node != null) {
			inOrderTraverse(node.getLeft());
			System.out.println(node.getValue());
			inOrderTraverse(node.getRight());
		}
	}
//中序遍歷(非遞歸)
	public void nrInOrderTraverse() {
		
		Stack<Node> stack = new Stack<Node>();
		Node node = root;
		while (node != null || !stack.isEmpty()) {
			while (node != null) {
				stack.push(node);
				node = node.getLeft();
			}
			node = stack.pop();
			System.out.println(node.getValue());
			node = node.getRight();
			
		}
				
	}
	//先序遍歷(遞歸)
	public void preOrderTraverse() {
		preOrderTraverse(root);
	}
	
	public void preOrderTraverse(Node node) {
		if (node != null) {
			System.out.println(node.getValue());
			preOrderTraverse(node.getLeft());
			preOrderTraverse(node.getRight());
		}
	}
//先序遍歷(非遞歸)
	public void nrPreOrderTraverse() {
		
		Stack<Node> stack = new Stack<Node>();
		Node node = root;
		
		while (node != null || !stack.isEmpty()) {
			
			while (node != null) {
				System.out.println(node.getValue());
				stack.push(node);
				node = node.getLeft();
			}
			node = stack.pop();
			node = node.getRight();
		}
				
	}
	
	//後序遍歷(遞歸)
	public void postOrderTraverse() {
		postOrderTraverse(root);
	}
	
	public void postOrderTraverse(Node node) {
		if (node != null) {
			postOrderTraverse(node.getLeft());
			postOrderTraverse(node.getRight());
			System.out.println(node.getValue());
		}
	}
	
	//後續遍歷(非遞歸)
	public void nrPostOrderTraverse() {
		
		Stack<Node> stack = new Stack<Node>();
		Node node = root;
		Node preNode = null;//表示最近一次訪問的節點
		
		while (node != null || !stack.isEmpty()) {
			
			while (node != null) {
				stack.push(node);
				node = node.getLeft();
			}
			
			node = stack.peek();
			
			if (node.getRight() == null || node.getRight() == preNode) {
				System.out.println(node.getValue());
				node = stack.pop();
				preNode = node;
				node = null;
			} else {
				node = node.getRight();
			}
			
		}
}
	
	//按層次遍歷
	public void levelTraverse() {
		levelTraverse(root);
	}
	
	public void levelTraverse(Node node) {
	
		Queue<Node> queue = new LinkedBlockingQueue<Node>();
		queue.add(node);
		while (!queue.isEmpty()) {
			
			Node temp = queue.poll();
			if (temp != null) {
				System.out.println(temp.getValue());
				queue.add(temp.getLeft());
				queue.add(temp.getRight());
			}
						
		}
				
	}
}
//樹的節點
class Node {
	
	private Node left;
	private Node right;
	private T value;
	
	public Node() {
	}
	public Node(Node left,Node right,T value) {
		this.left = left;
		this.right = right;
		this.value = value;
	}
	
	public Node(T value) {
		this(null,null,value);
	}
	public Node getLeft() {
		return left;
	}
	public void setLeft(Node left) {
		this.left = left;
	}
	public Node getRight() {
		return right;
	}
	public void setRight(Node right) {
		this.right = right;
	}
	public T getValue() {
		return value;
	}
	public void setValue(T value) {
		this.value = value;
	}
		
}
測試代碼:
package com.algorithm.tree;
public class TreeTest {
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Tree tree = new Tree();
		tree.buildTree();
		System.out.println("中序遍歷");
		tree.inOrderTraverse();
		tree.nrInOrderTraverse();
		System.out.println("後續遍歷");
		//tree.nrPostOrderTraverse();
		tree.postOrderTraverse();
		tree.nrPostOrderTraverse();
		System.out.println("先序遍歷");
		tree.preOrderTraverse();
		tree.nrPreOrderTraverse();
		
//
	}
}
㈥ java 構建二叉樹
首先我想問為什麼要用LinkedList 來建立二叉樹呢? LinkedList 是線性表,
樹是樹形的, 似乎不太合適。
其實也可以用數組完成,而且效率更高.
關鍵是我覺得你這個輸入本身就是一個二叉樹啊,
String input = "ABCDE F G";
節點編號從0到8. 層次遍歷的話:
對於節點i.
leftChild = input.charAt(2*i+1); //做子樹
rightChild = input.charAt(2*i+2);//右子樹
如果你要將帶有節點信息的樹存到LinkedList裡面, 先建立一個節點類:
class Node{
  public char cValue;
  public Node leftChild;
  public Node rightChild;
  public Node(v){
     this.cValue = v;
  }
}
然後遍歷input,建立各個節點對象.
LinkedList tree = new LinkedList();
for(int i=0;i< input.length;i++)
   LinkedList.add(new Node(input.charAt(i)));
然後為各個節點設置左右子樹:
for(int i=0;i<input.length;i++){
   ((Node)tree.get(i)).leftChild = (Node)tree.get(2*i+1);
   ((Node)tree.get(i)).rightChild = (Node)tree.get(2*i+2);
}
這樣LinkedList 就存儲了整個二叉樹. 而第0個元素就是樹根,思路大體是這樣吧。
㈦ java如何創建一顆二叉樹
計算機科學中,二叉樹是每個結點最多有兩個子樹的有序樹。通常子樹的根被稱作「左子樹」(left subtree)和「右子樹」(right subtree)。二叉樹常被用作二叉查找樹和二叉堆或是二叉排序樹。
二叉樹的每個結點至多隻有二棵子樹(不存在度大於2的結點),二叉樹的子樹有左右之分,次序不能顛倒。二叉樹的第i層至多有2的 i -1次方個結點;深度為k的二叉樹至多有2^(k) -1個結點;對任何一棵二叉樹T,如果其終端結點數(即葉子結點數)為n0,度為2的結點數為n2,則n0 = n2 + 1。
樹是由一個或多個結點組成的有限集合,其中:
⒈必有一個特定的稱為根(ROOT)的結點;
二叉樹
⒉剩下的結點被分成n>=0個互不相交的集合T1、T2、......Tn,而且, 這些集合的每一個又都是樹。樹T1、T2、......Tn被稱作根的子樹(Subtree)。
樹的遞歸定義如下:(1)至少有一個結點(稱為根)(2)其它是互不相交的子樹
1.樹的度——也即是寬度,簡單地說,就是結點的分支數。以組成該樹各結點中最大的度作為該樹的度,如上圖的樹,其度為2;樹中度為零的結點稱為葉結點或終端結點。樹中度不為零的結點稱為分枝結點或非終端結點。除根結點外的分枝結點統稱為內部結點。
2.樹的深度——組成該樹各結點的最大層次。
3.森林——指若干棵互不相交的樹的集合,如上圖,去掉根結點A,其原來的二棵子樹T1、T2、T3的集合{T1,T2,T3}就為森林;
4.有序樹——指樹中同層結點從左到右有次序排列,它們之間的次序不能互換,這樣的樹稱為有序樹,否則稱為無序樹。
樹的表示
樹的表示方法有許多,常用的方法是用括弧:先將根結點放入一對圓括弧中,然後把它的子樹由左至右的順序放入括弧中,而對子樹也採用同樣的方法處理;同層子樹與它的根結點用圓括弧括起來,同層子樹之間用逗號隔開,最後用閉括弧括起來。如右圖可寫成如下形式:
二叉樹
(a( b(d,e), c( f(    ,g(h,i) ),    )))
㈧ 用java建立二叉樹
數據結構的教材里有,
建立兩個類就應該可以了。
一個是樹的節點,一個是樹,這個是我以前編寫的寬度優先遍歷的樹的構建和遍歷,希望對你有幫助。文件名是:Tree.java
import java.util.ArrayList;
// 樹的一個節點
class TreeNode {
    Object _value = null; // 他的值
    TreeNode _parent = null; // 他的父節點,根節點沒有PARENT
    ArrayList _childList = new ArrayList(); // 他的孩子節點
    public TreeNode( Object value, TreeNode parent ){
        this._parent = parent;
        this._value = value;
    }
    public TreeNode getParent(){
        return _parent;
    }
    public String toString() {
        return _value.toString();
    }
}
public class Tree {
    // 給出寬度優先遍歷的值數組,構建出一棵多叉樹
    // null 值表示一個層次的結束
    // "|" 表示一個層次中一個父親節點的孩子輸入結束
    // 如:給定下面的值數組:
    // { "root", null, "left", "right", null }
    // 則構建出一個根節點,帶有兩個孩子("left","right")的樹
    public Tree( Object[] values ){
        // 創建根
        _root = new TreeNode( values[0], null );
        // 創建下面的子節點
        TreeNode currentParent = _root; // 用於待創建節點的父親
        //TreeNode nextParent = null;
        int currentChildIndex = 0; // 表示 currentParent 是他的父親的第幾個兒子
        //TreeNode lastNode = null; // 最後一個創建出來的TreeNode,用於找到他的父親
        for ( int i = 2; i < values.length; i++ ){
            // 如果null ,表示下一個節點的父親是當前節點的父親的第一個孩子節點
            if ( values[i] == null ){
                currentParent = (TreeNode)currentParent._childList.get(0);
                currentChildIndex = 0;
                continue;
            }
            // 表示一個父節點的所有孩子輸入完畢
            if ( values[i].equals("|") ){
                if ( currentChildIndex+1 < currentParent._childList.size() ){
                    currentChildIndex++;
                    currentParent = (TreeNode)currentParent._parent._childList.get(currentChildIndex);
                }
                continue;
            }
            TreeNode child = createChildNode( currentParent, values[i] );
        }
    }
    TreeNode _root = null;
    public TreeNode getRoot(){
        return _root;
    }
/**
    // 按寬度優先遍歷,列印出parent子樹所有的節點
    private void printSteps( TreeNode parent, int currentDepth ){
        for ( int i = 0; i < parent._childList.size(); i++ ){
            TreeNode child = (TreeNode)parent._childList.get(i);
            System.out.println(currentDepth+":"+child);
        }
        if ( parent._childList.size() != 0 )    System.out.println(""+null);// 為了避免葉子節點也會列印null
        //列印 parent 同層的節點的孩子
        if ( parent._parent != null ){ // 不是root
            int i = 1;
            while ( i < parent._parent._childList.size() ){// parent 的父親還有孩子
                TreeNode current = (TreeNode)parent._parent._childList.get(i);
                printSteps( current, currentDepth );
                i++;
            }
        }
// 遞歸調用,列印所有節點
        for ( int i = 0; i < parent._childList.size(); i++ ){
            TreeNode child = (TreeNode)parent._childList.get(i);
            printSteps( child, currentDepth+1 );
        }
    }
    // 按寬度優先遍歷,列印出parent子樹所有的節點
    public void printSteps(){
        System.out.println(""+_root);
        System.out.println(""+null);
        printSteps(_root, 1 );
    }**/
    // 將給定的值做為 parent 的孩子,構建節點
    private TreeNode createChildNode( TreeNode parent, Object value ){
        TreeNode child = new TreeNode( value , parent );
        parent._childList.add( child );
        return child;
    }
    public static void main(String[] args) {
        Tree tree = new Tree( new Object[]{ "root", null,
                              "left", "right", null,
                              "l1","l2","l3", "|", "r1","r2",null } );
        //tree.printSteps();
        System.out.println(""+ ( (TreeNode)tree.getRoot()._childList.get(0) )._childList.get(0) );
        System.out.println(""+ ( (TreeNode)tree.getRoot()._childList.get(0) )._childList.get(1) );
        System.out.println(""+ ( (TreeNode)tree.getRoot()._childList.get(0) )._childList.get(2) );
        System.out.println(""+ ( (TreeNode)tree.getRoot()._childList.get(1) )._childList.get(0) );
        System.out.println(""+ ( (TreeNode)tree.getRoot()._childList.get(1) )._childList.get(1) );
    }
}
