Given a binary tree rooted at root, the depth of each node is the shortest distance to the root. A node is deepest if it has the largest depth possible among any node in the entire tree. The subtree of a node is that node, plus the set of all descendants of that node. Return the node with the largest depth such that it contains all the deepest nodes in its subtree.
publicclassSmallestSubtree{ public TreeNode subtreeWithAllDeepest(TreeNode root){ return dfs(root).node; }
// Return the result of the subtree at this node. public Result dfs(TreeNode node){ if (node == null) returnnew Result(null, 0); Result L = dfs(node.left), R = dfs(node.right); if (L.dist > R.dist) returnnew Result(L.node, L.dist + 1); if (L.dist < R.dist) returnnew Result(R.node, R.dist + 1); returnnew Result(node, L.dist + 1); } }
classResult{ TreeNode node; int dist;
Result(TreeNode n, int d) { node = n; dist = d; } }
classTreeNode{ int val; TreeNode left; TreeNode right;
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree [1,2,2,3,4,4,3] is symmetric:
1 2 3 4 5
1 / \ 2 2 / \ / \ 3 4 4 3
But the following [1,2,2,null,3,null,3] is not:
1 2 3 4 5
1 / \ 2 2 \ \ 3 3
To solve this problem, we need to do pair comparisons recursively. For example, if we want to check whether the following array is symmetric, we need to use two pointers to traverse and compare pairs of values:
1 2 3 4 5 6 7 8
[1, 2, 3, 3, 2, 1] ⬆ ⬆
[1, 2, 3, 3, 2, 1] ⬆ ⬆
[1, 2, 3, 3, 2, 1] ⬆ ⬆
In this problem, we need to compare pairs of subtrees:
publicclassSymmetricTree{ publicbooleanisSymmetric(TreeNode root){ // if root == null, it is symmetric // if root != null, we need to check w return root == null || check(root.left, root.right); }
publicbooleancheck(TreeNode left, TreeNode right){ if(left == null || right == null) { return left == right; }
publicclassBinaryTreeRightSideView{ public List<Integer> rightSideView(TreeNode root){ List<Integer> result = new ArrayList<>(); if (root == null) { return result; }
Queue<TreeNode> queue = new LinkedList<>(); queue.add(root); while (!queue.isEmpty()) { int size = queue.size(); for (int i = 0; i < size; i++) { TreeNode currentNode = queue.remove();
if(i == size - 1) {// the last node at each level result.add(currentNode.val); }
Given an array where elements are sorted in ascending order, convert it to a height balanced BST. For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
1 2 3 4 5 6 7 8 9
Example: Given the sorted array: [-10,-3,0,5,9], One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:
0 / \ -3 9 / / -10 5
Because the array is sorted, we can use the idea of binary search to solve this problem: