General
104 Max depth
public int maxDepth(TreeNode root) { if(root == null) return 0;
return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;}
111 Min depth
public int minDepth(TreeNode root) {
if(root == null) return 0;
if(root.left == null) return minDepth(root.right) + 1;
if(root.right == null) return minDepth(root.left) + 1;
return Math.min(minDepth(root.left), minDepth(root.right)) + 1;
}110 Check Balanced
a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
public boolean isBalanced(TreeNode root) {
return maxDepth(root) == -1 ? false : true;
}
private int maxDepth(TreeNode root){
if(root == null) return 0;
int left = maxDepth(root.left);
int right = maxDepth(root.right);
if(left == -1 || right == -1 || Math.abs(left-right) > 1) return -1;
return Math.max(left, right) + 1;
}285 Inorder Successor/Predecessor in BST
Given a binary search tree and a node in it, find the in-order successor of that node in the BST.
Note: If the given node has no in-order successor in the tree, return null.

Successor
Predecessor
654 Maximum Binary Tree
Given an integer array with no duplicates. A maximum tree building on this array is defined as follow:
The root is the maximum number in the array.
The left subtree is the maximum tree constructed from left part subarray divided by the maximum number.
The right subtree is the maximum tree constructed from right part subarray divided by the maximum number.
Divide and Conquer, use getTree construct tree and findMax find max index.
Average time O(nlogn), worst case O(n^2)
222 Count Complete TreeNode
Given a complete binary tree, count the number of nodes.
Time O(n)
每一層leftNode or rightNode有一個是complete tree, 總共logn層
Time O(logn)
863. All Nodes Distance K in Binary Tree
Return a list of the values of all nodes that have a distance K from the target node.

1145. Binary Tree Coloring Game
Two players play a turn based game on a binary tree. We are given the root of this binary tree, and the number of nodes n in the tree. n is odd, and each node has a distinct value from 1 to n.
The first player colors the node with value x red, and the second player colors the node with value y blue.
return if second player can win the game
The best chance to win is choosing node next to x, the players 1 can't cross this node, players can take the child nodes all.
3 possibilities: left child, right child, and parent node
Return if candidate subtree is greater than total number of nodes
Last updated
Was this helpful?