左神算法笔记之二叉树——二叉树宽度、搜索二叉树、完全二叉树、满二叉树、平衡二叉树、两棵二叉树的最低公共祖先节点、二叉树中某个节点的后继节点、二叉树的序列化和反序列化

这篇博客详细讲解了二叉树的各种特性与操作,包括如何进行宽度优先遍历以求取二叉树的宽度,判断一棵树是否为搜索二叉树、完全二叉树、满二叉树及平衡二叉树的方法,同时还探讨了如何找到两棵二叉树的最低公共祖先节点,以及在中序遍历中寻找特定节点的后继节点。此外,还介绍了二叉树的序列化和反序列化技术。
摘要由CSDN通过智能技术生成

一、二叉树宽度优先遍历和求二叉树宽度

public class bfsTree{
   
	public static class Node{
   
		public int value;
		public Node left;
		public Node right;
		
		public Node(int data){
   
			this.value = data;
		}
	}

	//宽度优先遍历
	public static void bfs(Node head){
   
		if(head == null){
   
			return;
		}
		Queue<Node> queue = new LinkerList<>();
		queue.add(head);
		while(!queue.isEmpty()){
   
			Node cur = queue.poll();
			System.out.println(cur.value);
			if(cur.left != null){
   
				queue.add(cur.left);
			}
			if(cur.right != null){
   
				queue.add(cur.right);
			}
		}
	}


	//二叉树宽度
	public static int W(Node head){
   
		if(head == null){
   
			return 0;
		}
		Queue<Node> queue = new LinkedList<>();
		queue.add(head);
		HashMap<Node,Integer> levelMap = new HashMap<>();
		levelMap.put(head,1);
		int curLevel = 1;
		int curLevelNodes = 0;
		int max = Integer.MIN_VALUE;
		while(!queue.isEmpty()){
   
			Node cur = queue.poll();
			int curNodeLevel = levelMap.get(cur);
			if(curNodeLevel == curLevel){
   
				curLevelNodes++;
			}else{
   
				max = Math.max(max,curLevelNodes);
				curLevel++;
				curLevelNodes = 1;
			}
			if(cur.left != null){
   
				levelMap.put(cur.left,curLevel+1);
				queue.add(cur.left);
			if(cur.right != null){
   
				levelMap.put(cur.right,curLevel+1);
				queue.add(cur.right);
			}
		}
		return max;
	}

}
		

二、判断一棵树是否是搜索二叉树

//搜索二叉树:每棵子树的左树都比头节点小,右树都比头节点大
public class CheckBST {
   
    public static class Node {
   
        public int value;
        public Node left;
        public Node right;

        public Node(int data
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值