关于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,说明没有这个
如果有两个都有值,那就是这个了。这个再写一下