栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

二叉树的递归套路——满二叉树

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

二叉树的递归套路——满二叉树

给定一棵二叉树的头节点head,返回这颗二叉树是不是满二叉树

特点:如果一颗二叉树的有L层,结点个数是N个的话,必定满足以下这个公式:
(2^L)-1 == N,且只有满二叉树有这个特点

根据二叉树的递归套路,以及满二叉树的特点,我们向每颗子树要的信息就是高度和结点个数。比较简单,就不赘述了。直接看代码叭:

package com.harrison.class08;

public class Code05_IsFull {
	public static class Node {
		public int value;
		public Node left;
		public Node right;

		public Node(int data) {
			this.value = data;
		}
	}
	
	public static class Info{
		public int height;
		public int nodes;
		
		public Info(int h,int n) {
			height=h;
			nodes=n;
		}
	}
	
	public static Info process1(Node head) {
		if(head==null) {
			return new Info(0, 0);
		}
		Info leftInfo=process1(head.left);
		Info righInfo=process1(head.right);
		int height=Math.max(leftInfo.height, righInfo.height)+1;
		int nodes=leftInfo.nodes+righInfo.nodes+1;
		return new Info(height, nodes);
	}
	
	public static boolean isFull1(Node head) {
		if(head==null) {
			return true;
		}
		Info allInfo=process1(head);
		return (1< maxLevel || Math.random() < 0.5) {
			return null;
		}
		Node head = new Node((int) (Math.random() * maxValue));
		head.left = generate(level + 1, maxLevel, maxValue);
		head.right = generate(level + 1, maxLevel, maxValue);
		return head;
	}

	public static void main(String[] args) {
		int maxLevel = 5;
		int maxValue = 100;
		int testTimes = 1000000;
		for (int i = 0; i < testTimes; i++) {
			Node head = generateRandomBST(maxLevel, maxValue);
			if (isFull1(head) != isFull2(head)) {
				System.out.println("Oops!");
			}
		}
		System.out.println("finish!");
	}
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/665925.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号