
When doing LeetCode problems, some corner cases should be considered when traversing through the tree, otherwise unexpected errors shall appear. Examples:
Symmetric Tree
Same Tree
The following code takes Symmetric Tree as an example:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22public void method(TreeNode root) {
    if (root == null) {
        return something;
    }
 
    // when the node is leaf node
    if (root.left == null && root.right == null) {
        return something;
    }
 
    // when the node has both children
    if (root.left != null && root.right != null) {
        if (root.left.val == root.right.val) {
            do something;
        } else {
            do something;
        }
    }
 
    // when the node is not leaf node yet
    do something;
}