java-75-二叉树两结点的最低共同父结点


import java.util.LinkedList;
import java.util.List;

import ljn.help.*;
public class BTreeLowestParentOfTwoNodes {

public static void main(String[] args) {
/*
* node data is stored in leverOrder.'0' represents null node.
* e.g.
* int[] data={1,8,7,9,2,0,0,0,0,4,7};
* the tree is:
* 1
/ \
8 7
/ \
9 2
/ \
4 7
*/
int[] data={1,8,7,9,2,0,0,0,0,4,7};
Node head=Helper.createTree(data);
Node node1=new Node(4);
Node node2=new Node(9);//their lowest parent should be 8
LinkedList<Node> path1=new LinkedList<Node>();//should be 1,8,2,4
LinkedList<Node> path2=new LinkedList<Node>();//should be 1,8,9
createPath(head,node1,path1);
createPath(head,node2,path2);
Node lowestParent=lastCommonNode(path1,path2);
System.out.println(lowestParent.getData());
}

//create a path from BTree's root to the specific node
public static boolean createPath(Node head,Node node,LinkedList<Node> path){
if(head.getData()==node.getData()){
return true;
}
boolean found=false;
path.addLast(head);
if(head.getLeft()!=null){
found=createPath(head.getLeft(),node,path);
}
if(!found&&head.getRight()!=null){
found=createPath(head.getRight(),node,path);
}
if(!found){
path.removeLast();
}
return found;
}
/*
* find 'lastCommonNode' of two list and return.
* e.g
* list1=1,2,3,5
* list2=1,2,3,4
* we return 3
*/
public static Node lastCommonNode(List<Node> list1,List<Node> list2){
Node result=null;
int len1=list1.size();
int len2=list2.size();
if(len1==0||len2==0){
return null;
}
for(int i=0,j=0;i<len1&&j<len2;i++,j++){
if(list1.get(i)==list2.get(j)){
result=list1.get(i);
}
}
return result;
}
}

Java 中,可以使用一个 Node 类来表示二叉树结点,并使用一个 BinaryTree 类来表示整个二叉树。以下是一个简单的示例代码,演示如何添加一个新的结点二叉树中: ``` // Node 类表示二叉树结点 class Node { int data; // 结点的数据 Node left, right; // 左子结点和右子结点 public Node(int data) { this.data = data; left = right = null; } } // BinaryTree 类表示整个二叉树 class BinaryTree { Node root; // 根结点 public BinaryTree() { root = null; } // 添加一个新的结点二叉树中 public void add(int data) { Node newNode = new Node(data); // 创建新的结点 if (root == null) { // 如果根结点为空,则把新结点作为根结点 root = newNode; return; } Node current = root; Node parent = null; while (true) { parent = current; if (data < current.data) { // 如果新结点的值比当前结点小,向左遍历 current = current.left; if (current == null) { // 如果左子结点为空,就把新结点插入到左子结点的位置 parent.left = newNode; return; } } else { // 如果新结点的值比当前结点大,向右遍历 current = current.right; if (current == null) { // 如果右子结点为空,就把新结点插入到右子结点的位置 parent.right = newNode; return; } } } } } ``` 在上面的代码中,add() 方法接收一个整数作为参数,表示要添加的新结点的值。首先,它创建一个新的结点,然后根据二叉树的性质,将新结点插入到二叉树中的合适位置。如果二叉树为空,就把新结点作为根结点。如果二叉树不为空,就从根结点开始遍历二叉树,向左或向右遍历,直到找到一个空结点,然后把新结点插入到这个空结点的位置。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值