Leetcode tree的碎碎念

關於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,說明沒有這個

如果有兩個都有值,那就是這個了。這個再寫一下


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章