剑指offer面试题39 二叉树的深度

考察点

树的遍历

知识点

题目

分析
本题目要求二叉树的深度,遇到树的题目思维肯定要往递归的方向上靠,假如左子树的深度和右子树的深度都求出来了,如何求根结点的深度?肯定是左右子树深度最大值+1,那么这道题目的算法也就出来了

public class Node{
	int val;
	Node leftChild;
	Node rightChild;

	public Node(int data) {
		this.val = data;
		this.leftChild = null;
		this.rightChild = null;
	}
}
public class BinaryTree {
	Node root;

	public BinaryTree() {
		this.root = null;
	}
	public void insertTree(int val) {
		if (this.root == null) {
			Node root = new Node(val);
			this.root = root;
		} else {
			insertChildTree(this.root,val);
		}
	}
	public void insertChildTree(Node node,int val) {
		if (node != null && val <= node.val) {
			if (node.leftChild == null) {
				node.leftChild = new Node(val);
			} else {
				insertChildTree(node.leftChild,val);
			}
		}
		if (node != null && val > node.val) {
			if (node.rightChild == null) {
				node.rightChild = new Node(val);
			} else {
				insertChildTree(node.rightChild,val);
			}
		}
	}
	public Node getRoot() {
		return this.root;
	}
	public int getDeep(Node node) {
		if(node == null) {
			return 0;
		}
		int left = getDeep(node.leftChild);
		int right = getDeep(node.rightChild);
		return left > right ? left+1:right+1;
	}
}
public class ThirtyNine {
	public static void main(String[] args) {
		BinaryTree binaryTree = new BinaryTree();
		binaryTree.insertTree(7);
		binaryTree.insertTree(3);
		binaryTree.insertTree(8);
		binaryTree.insertTree(1);
		binaryTree.insertTree(5);
		binaryTree.insertTree(4);
		System.out.println(binaryTree.getDeep(binaryTree.getRoot()));
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值