1. 程式人生 > >樹中兩個結點的最低公共祖先(Java)

樹中兩個結點的最低公共祖先(Java)

題目:

樹中兩個結點的最低公共祖先。

解決方法一:

假設是二叉搜尋樹(二叉搜尋樹是一個排序的二叉樹,左子樹的結點小於根結點,右子樹的結點大於根結點),故找到一個結點,使其大於左子結點小於右子結點即可。

程式碼實現:

public static TreeNode getLastCommonNode(TreeNode pRoot, TreeNode pLeft, TreeNode pRight){
	TreeNode treeNode = null;
	if(pRoot == null || pLeft.val > pRight.val){
		return null;
	}
	if(pRoot.val >= pRight.val){
		treeNode = getLastCommonNode(pRoot.left, pLeft, pRight);
	}
	if(pRoot.val <= pLeft.val){
		treeNode = getLastCommonNode(pRoot.right, pLeft, pRight);
	}
	if(pRoot.val >= pLeft.val && pRoot.val <= pRight.val){
		return pRoot;
	}
	return treeNode;
}

解決方法二:

假設是普通的二叉樹。遞迴遍歷找到所給定的兩個結點,然後向上標記,直到有一個結點的左子結點和右子結點都不為空返回即可。

public static BTreeNode getLastCommonNode(BTreeNode pRoot, BTreeNode pLeft, BTreeNode pRight){
	//發現目標節點則通過返回值標記該子樹發現了某個目標結點
	if(pRoot == null || pRoot == pLeft || pRoot == pRight){
		return pRoot;
	}
	//檢視左子樹中是否有目標結點,沒有為null
	BTreeNode left = getLastCommonNode(pRoot.left, pLeft, pRight);
	//檢視右子樹是否有目標節點,沒有為null
	BTreeNode right = getLastCommonNode(pRoot.right, pLeft, pRight);
	//都不為空,說明做右子樹都有目標結點,則公共祖先就是本身
	if(left != null && right != null){
		return pRoot;
	}
	//如果發現了目標節點,則繼續向上標記為該目標節點
	return left == null ? right : right;
}

解決方法三:

假設是普通的樹,但是每個子結點都有指向父結點的指標,這樣的話類似與前面的連結串列找公共結點一樣。

解決方法四:

假設就是一棵普通的數,子結點沒有指向父結點的指標。

public static TreeNode getLastCommonParent(TreeNode pRoot, TreeNode p1, TreeNode p2){
	//儲存p1的路徑
	ArrayList<TreeNode> path1 = new ArrayList<TreeNode>();
	//儲存p2的路徑
	ArrayList<TreeNode> path2 = new ArrayList<TreeNode>();
	ArrayList<TreeNode> tmpList = new ArrayList<TreeNode>();
	getNodePath(pRoot, p1, tmpList, path1);
	getNodePath(pRoot, p2, tmpList, path2);
	//如果路徑不存在,返回空
	if(path1.size() == 0 || path2.size() == 0){
		return null;
	}
	return getLastCommonParent(path1, path2);
}

//獲取根節點到目標節點的路徑
public static void getNodePath(TreeNode pRoot, TreeNode pNode, ArrayList<TreeNode> tmpList, ArrayList<TreeNode> path){
	if(pRoot == pNode || pRoot == null){
		return ;
	}
	tmpList.add(pRoot);
	ArrayList<TreeNode> childs = pRoot.children;
	for(TreeNode node : childs){
		if(node == pNode){
			path.addAll(tmpList);
			break;
		}
		getNodePath(node, pNode, tmpList, path);
	}
	tmpList.remove(tmpList.size()-1); //清空集合
}
	
private static TreeNode getLastCommonParent(ArrayList<TreeNode> path1, ArrayList<TreeNode> path2) {
	TreeNode tmpNode = null;
	for(int i = 0; i < path1.size(); i++){
		if(path1.get(i)!=path2.get(i)){
			break;
		}
	    //迴圈結束時tmpNode即為最後一個共同結點
		tmpNode = path1.get(i);
	}
	return tmpNode;
}