PTA 玩转二叉树 java

这篇博客主要介绍了如何使用Java解决PTA平台上的二叉树题目,包括两个特定题目:树的遍历。解题关键在于正确构建二叉树的过程,详细解析可参考给出的优快云链接。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

PTA 玩转二叉树题目:https://pintia.cn/problem-sets/1120858298571182080/problems/1120858493795061760

与 PTA 树的遍历题目https://pintia.cn/problem-sets/1120858298571182080/problems/1120858728923549696

解法几乎完全一致,核心是建树过程,请参看PTA 树的遍历题解:

https://blog.youkuaiyun.com/aiwo1376301646/article/details/93496863

 

package pat树;
//ac
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

public class Main8玩转二叉树 {
    static int n;
    static int[]id;
    static int[]pr;
    static Queue<node>q=new LinkedList<node>();
    
    public static node build(int prl,int prr,int il,int ir) {
    	if(il>ir) return null;
    	node root=new node();
    	int v=pr[prl];
    	root.v=v;
    	int i;
    	for(i=il;i<=ir;i++)if(id[i]==v)break;
    	int num=i-il;
    	//镜面反转,是指将所有非叶结点的左右孩子对换
    	//把比根节点大的建在根节点的左边,比根节点小的建在根节点的右边
    	root.le=build(prl+num+1,prr,i+1,ir);
    	root.ri=build(prl+1,prl+num,il,i-1);
    	return root;
    	
    }
    public static void print() {
    	int t=1;
    	while(!q.isEmpty()) {
    		node r=q.poll();
    		if(t==n)System.out.println(r.v);
    		else {
    			System.out.print(r.v+" ");
    			t++;
    		}
    		if(r.le!=null)q.add(r.le);
    		if(r.ri!=null)q.add(r.ri);
    	}
    }
	public static void main(String[] args) {
		Scanner in=new Scanner(System.in);
	    n=in.nextInt();
	    id=new int[n+1];
	    pr=new int[n+1];
	    for(int i=1;i<=n;i++)id[i]=in.nextInt();
	    for(int i=1;i<=n;i++)pr[i]=in.nextInt();
	    node root=build(1,n,1,n);
	    q.add(root);
	    print();
	    

	}

}
class node{
	int v;
	node le;
	node ri;
	
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值