Leetcode tree的碎碎念

11 篇文章 0 订阅

关于Leetcode 中的Tree应该是最简单的一类题。


绝大部分题考察队树的遍历,前序,中序,后序对树的遍历。


然后还有各种变形体考对树的遍历,


还有其他题型考对树的前序遍历 path sum, the maximum depth, and the minimum depth of the tree.  They all need to record return the value when reach the leafNode.

that means that if the right and the left is all null then return the result. like


public void helper(TreeNode tem, int sum){
	sum = sum + tem.val;
	if((tem.right == null && tem.left == null) && sum > maxValue){
		maxValue = sum;
		return;
	}
	//This is pretraverse code, because it first add the value of the current node to the result, result = result + tem.val. Then it go to the left or right children of the current node
	if(tem.left != null)
		helper(tem.left, sum);	
	if(tem.right != null)
		helper(tem.right, sum);
}	

another kind of tree is to do the postorder like symmeric tree. Balanced binary search tree, we need to traverse the leaf node to get computation result about the current code.

For example, if we want to know if this node is a balance search tree. We have to judge the balanced tree. the left children is balanced tree and the right children is balanced tree and we need to return the height value for for the current tree. and we need to make sure that the absolute value for the difference of the height of left children and the right children is less or equal to 1. if the node is null we need to return 0. the for this node we need to 

public int helper(TreeNode tem){
	if(tem.left == null && tem.right == null)
		return 1;
	int left = 0;
	if(tem != null)
		left = helper(tem.left);
	int right = 0;
	if(tem != null)
		right = helper(tem.right);
	if(left == -1 || right == -1)
		return -1;
	if(Math.abs(left - right) > 1)
		return -1;
	return Math.max(left, right) + 1;
}

So that means that we need to do the helper function to first traverse the left and right nodes. and the return the value for itself. So it is a postorder traverse.


另外还应该注意的题有

235. Lowest Common Ancestor of a Binary Search Tree

利用Binary serach tree的性质来找common Ancestor. 就是都小于往左边,都大于往右边


235. Lowest Common Ancestor of a Binary Search Tree

左右两边分别查找,如果都有一个为null,说明没有这个

如果有两个都有值,那就是这个了。这个再写一下


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值