尋找父節點

尋找父節點,實現過程如下所示:

package cn.edu.nwu.structs.tree;
/**
 * @author jcm
 *	找父節點
 * 時間 2016年9月1日
 */
public class GetFatherTreeNode {
	public static int father = -1;
	public static void main(String[] args) {
		BinaryTreeNode root = CreateBinaryTree.createBinaryTree();
		show(root,1);
		getFatherTreeNode(root,4);
		System.out.println(father);
	}
	/**
	 * @author jcm
	 *  找該節點的父節點,並且打印
	 * @param root
	 * @param data
	 */
	public static void getFatherTreeNode(BinaryTreeNode root,int data){
		if(root == null){
			return;
		}
		//如果找到該節點,則把父節點的數據複製給全局變量
		if(root.leftTreeNode != null && root.leftTreeNode.data == data){
			father = root.data;
		}
		if(root.rightTreeNode != null && root.rightTreeNode.data == data){
		}
		//遞歸調用
		getFatherTreeNode(root.leftTreeNode,data);
		getFatherTreeNode(root.rightTreeNode,data);
	}
	public static void show(BinaryTreeNode root, int n) {
		if (root == null) {
			return;
		} else {
			show(root.leftTreeNode, n + 1);
			for (int i = 0; i < n; i++) {
				System.out.print("	");
			}
			System.out.println(root.data);
			show(root.rightTreeNode, n + 1);
		}
	}
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章