问题 Given the root of a Binary Search Tree and a target number k, return true if there exist two elements in the BST such that their sum is equal to the given target.
问题 Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”
DFS搜索,如果当前节点为null,则返回null。 如果当前节点小于p和q的值,则递归其左子节点。 反之递归其右子节点。 如果当前节点在p与q之间,则返回当前节点。 该节点是p与q的Lowest Common Ancestor。
问题 Given the root of a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus the sum of all keys greater than the original key in BST.
As a reminder, a binary search tree is a tree that satisfies these constraints:
The left subtree of a node contains only >->- nodes with keys less than the node’s key.
The right subtree of a node contains only nodes with keys greater than the node’s key.
Both the left and right subtrees must also be binary search trees.
问题 Given the root of a binary search tree and the lowest and highest boundaries as low and high, trim the tree so that all its elements lies in [low, high]. Trimming the tree should not change the relative structure of the elements that will remain in the tree (i.e., any node’s descendant should remain a descendant). It can be proven that there is a unique answer.
Return the root of the trimmed binary search tree. Note that the root may change depending on the given bounds.
问题 Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum.
classSolution { List<List<Integer>> ans; public List<List<Integer>> combine(int n, int k) { ans = newArrayList<>(); backTrack(newLinkedList(),1,n,k); return ans; } privatevoidbackTrack(LinkedList<Integer> list, int start, int n, int k){ if (k == 0){ ans.add(newArrayList(list)); return; }
for (inti= start; i <= n-k+1; i++){ list.add(i); backTrack(list, i+1, n, k-1); list.removeLast(); } } }