最大 BST 子树(https://leetcode-cn.com/problems/largest-bst-subtree/)

法一:暴力枚举
直观的想法就是我枚举每一个节点,去检查这个节点为根的子树是不是一棵二叉搜索树,如果是的话就统计一下这个子树的节点数并更新答案,否则就继续递归到左右子树去找有没有符合条件的二叉搜索树。
时间复杂度:
public static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
public static int largestBSTSubtree(TreeNode root) {
if(root == null){
return 0;
}
if(isBiSearchTree(root, -Integer.MAX_VALUE, Integer.MAX_VALUE)){
return count(root, 0);
}
return Math.max(largestBSTSubtree(root.left), largestBSTSubtree(root.right));
}
// 计算二叉树的节点个数
public static int count(TreeNode root, int base){
if(root != null){
base++;
}
if(root.left != null){
base = count(root.left, base);
}
if(root.right != null){
base = count(root.right, base);
}
return base;
}
// 判断二叉树是否是搜索二叉树
public static boolean isBiSearchTree(TreeNode root, int min, int max){
if(root == null){
return true;
}
if(root.val <= min || root.val >= max){
return false;
}
if(root.left == null && root.right == null){
return true;
}
if(root.left == null && root.right != null){
return isBiSearchTree(root.right, root.val, max);
}
if(root.left != null && root.right == null){
return isBiSearchTree(root.left, min, root.val);
}
if(root.left != null && root.right != null){
return isBiSearchTree(root.left, min, root.val) && isBiSearchTree(root.right, root.val, max);
}
return false;
}
法二:复用子树信息
在法一判断root节点是否是搜索二叉树的时候,其实已经将所有节点是否是搜索二叉树计算了一遍,如果能够复用这些子树的信息,就可以降低时间复杂度为O(N)。
方法是从下往上搜索,如果子树不是搜索二叉树,那么当前树必然也不是;如果子树是搜索二叉树,那么要判断当前节点值是否大于左子树的最大值,是否小于右子树的最小值;
根据上面说的我们设计一个递归函数 recursion(TreeNode node) ,表示考虑当前节点是不是一棵二叉搜索树,先递归左右子树,拿到左右子树是不是二叉搜索树,以及相应值的范围,再根据上文说的更新当前的节点的信息即可。由于递归函数需要返回如下信息,则我们建一个结构体存储信息:
public static class Result{
boolean isBST; // 当前树是否是BST子树
int size; // 当前树的最大BST子树的节点个数
int max; // 当前树的最大节点值
int min; // 当前树的最小节点值
}
如果当前节点是二叉搜索树的话,则需要更新当前值的范围:max即为右子树的最大值,min即为左子树的最小值;size为左右子树的size之和再加1;如果当前节点不是二叉搜索树的话,那么之后此节点的父节点都不可能是二叉搜索树,size就取左右子树中大的那个,将isBST设置为false,而max和min值已经失去意义,不需要更新;然后再递归回上一层更新其父亲节点的信息,可以看出这是一个从下往上更新信息的过程。
public static int largestBSTSubtree(TreeNode root) {
if(root == null){
return 0;
}
Result result = recursion(root);
return result.size < 1 ? 1 : result.size;
}
public static Result recursion(TreeNode node){
if(node == null){
return null;
}
Result lRes = recursion(node.left);
Result rRes = recursion(node.right);
Result result = new Result();
boolean lValid = lRes == null || (lRes.isBST && node.val > lRes.max);
boolean rValid = rRes == null || (rRes.isBST && node.val < rRes.min);
// 当前树是BST
result.isBST = lValid && rValid;
if(lValid && rValid){
result.size = (lRes == null ? 0 : lRes.size) + (rRes == null ? 0 : rRes.size) + 1;
result.max = (rRes == null ? node.val : rRes.max);
result.min = (lRes == null ? node.val : lRes.min);
return result;
}
// 当前树不是BST, 那么只需要给size赋值, max和min已经没有意义
if(lRes != null && rRes != null){
result.size = lRes.size > rRes.size ? lRes.size : rRes.size;
}else if(lRes != null){
result.size = lRes.size;
}else if(rRes != null){
result.size = rRes.size;
}
return result;
}
二叉树的右视图(https://leetcode-cn.com/problems/binary-tree-right-side-view/)
给定一棵二叉树,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。
示例:
输入: [1,2,3,null,5,null,4]
输出: [1, 3, 4]
解释:

技巧总结:
二叉树的层序遍历(广度优先遍历)保留层数信息的两种方式:
1)使用两个队列,一个队列保存value值,一个队列同步保存对应value值的层数;
2)只使用一个队列,while循环中嵌套使用for循环,每次队列出队前读取当前队列的size,然后for循环中进行size次出队列,刚好可以处理完一层的节点。
广度优先
因为只需要保留每层中最右边的数即可:
1)先入队左儿子,再入队右儿子,那么每层中最右边的数,即每层中最后一个出队列的
2)如何得到每层的数量:在遍历之前读取queue的size即可;
public static List<Integer> rightSideView(TreeNode root) {
List<Integer> ret = new ArrayList<>();
if(root == null){
return ret;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
TreeNode node = queue.poll();
if (i == size - 1) {
ret.add(node.val);
}
if (node.left != null) {
queue.add(node.left);
}
if (node.right != null) {
queue.add(node.right);
}
}
}
return ret;
}
public static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
或者利用额外一个队列保存depth的信息,每入队或出队一个node,对应的depth queue就同样出队或者入队一个depth信息;
class Solution {
public List<Integer> rightSideView(TreeNode root) {
Map<Integer, Integer> rightmostValueAtDepth = new HashMap<Integer, Integer>();
int max_depth = -1;
Queue<TreeNode> nodeQueue = new LinkedList<TreeNode>();
Queue<Integer> depthQueue = new LinkedList<Integer>();
nodeQueue.add(root);
depthQueue.add(0);
while (!nodeQueue.isEmpty()) {
TreeNode node = nodeQueue.remove();
int depth = depthQueue.remove();
if (node != null) {
// 维护二叉树的最大深度
max_depth = Math.max(max_depth, depth);
// 由于每一层最后一个访问到的节点才是我们要的答案,因此不断更新对应深度的信息即可
rightmostValueAtDepth.put(depth, node.val);
nodeQueue.add(node.left);
nodeQueue.add(node.right);
depthQueue.add(depth+1);
depthQueue.add(depth+1);
}
}
List<Integer> rightView = new ArrayList<Integer>();
for (int depth = 0; depth <= max_depth; depth++) {
rightView.add(rightmostValueAtDepth.get(depth));
}
return rightView;
}
}
二叉树的锯齿形层次遍历

层序遍历二叉树(广度优先遍历)
此题需要知道层的信息,根据前面的总结,二叉树的层数信息可以有两种方式,1)使用额外队列同步保存level信息 2)使用while循环嵌套for循环,每次while循环的开始读取队列的size
这里使用第2)种,因为代码简洁。
使用一个bool变量表示当前层是奇数层还是偶数层,奇数层:list末尾添加;偶数层:list开头添加;
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> ret = new ArrayList<>();
if(root == null){
return ret;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
boolean isOddLevel = true;
while (!queue.isEmpty()){
int size = queue.size();
List<Integer> levelNums = new ArrayList<>();
for(int i=0; i<size; i++){
TreeNode currentNode = queue.poll();
if(isOddLevel){
levelNums.add(currentNode.val);
}else {
levelNums.add(0, currentNode.val);
}
if(currentNode.left != null){
queue.add(currentNode.left);
}
if(currentNode.right != null){
queue.add(currentNode.right);
}
}
ret.add(levelNums);
isOddLevel = !isOddLevel;
}
return ret;
}
从前序与中序遍历序列构造二叉树

递归解法

private Map<Integer, Integer> indexMap;
public TreeNode buildTree(int[] preorder, int[] inorder) {
if (preorder.length == 0) {
return null;
}
indexMap = new HashMap<>();
for (int i = 0; i < inorder.length; i++) {
indexMap.put(inorder[i], i);
}
return buildTree(preorder, inorder, 0, preorder.length - 1, 0, inorder.length - 1);
}
public TreeNode buildTree(int[] preorder, int[] inorder, int preStart, int preEnd, int inStart, int inEnd) {
if (preStart == preEnd) {
return new TreeNode(preorder[preStart]);
}
int rootValue = preorder[preStart];
TreeNode root = new TreeNode(rootValue);
int index = indexMap.get(rootValue);
int leftCount = index - inStart;
int rightCount = inEnd - index;
if (leftCount > 0) {
root.left = buildTree(preorder, inorder, preStart + 1, preStart + leftCount, inStart, index - 1);
}
if (rightCount > 0) {
root.right = buildTree(preorder, inorder, preStart + leftCount + 1, preEnd, index + 1, inEnd);
}
return root;
}
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
验证二叉搜索树

递归

public boolean isValidBST(TreeNode root) {
return recursion(root, null, null);
}
public boolean recursion(TreeNode node, Integer greatThan, Integer lessThan){
if(node == null){
return true;
}
if(greatThan != null && node.val <= greatThan){
return false;
}
if(lessThan != null && node.val >= lessThan){
return false;
}
if(node.left != null && !recursion(node.left, greatThan, node.val)){
return false;
}
if(node.right != null && !recursion(node.right, node.val, lessThan)){
return false;
}
return true;
}
二叉树展开为链表

递归
比较直观的思路如下:可用递归实现
1)递归将左子树展开为单链表L;
2)递归将右子树展开为单链表R;
3)将R链接到L末尾,合并成一个单链表;
4)将root的左子树置空,右子树指向上面合并的单链表;
官方讲解有很多更加简洁的递归写法,但是理解起来比较费力;这里还是用自己的递归写法,性能都是一样的。
public void flatten(TreeNode root) {
if(root == null){
return;
}
// 将左子树变成一个单链表
flatten(root.left);
// 将右子树变成一个单链表
flatten(root.right);
// 右子树为连接两个单链表的结果
root.right = link(root.left, root.right);
// 左子树置空
root.left = null;
}
public TreeNode link(TreeNode left, TreeNode right){
if(left == null){
return right;
}
TreeNode curr = left;
while (curr.right != null){
curr = curr.right;
}
curr.right = right;
return left;
}
迭代
1)将左子树插入到右子树的地方
2)将原来的右子树接到左子树的最右边节点
3)考虑新的右子树的根节点,一直重复上边的过程,直到新的右子树为 null


public void flatten(TreeNode root) {
while (root != null){
if(root.left == null){ // 左子树为 null,直接考虑下一个节点
root = root.right;
}else {
// 将左子树接到右子树的地方
TreeNode oriRight = root.right;
root.right = root.left;
root.left = null;
// 找到左子树(现在右子树)的最右边节点
TreeNode ptr = root.right;
while (ptr.right != null){
ptr = ptr.right;
}
// 将原来的右子树接到左子树(现在右子树)的最右边节点
ptr.right = oriRight;
root = root.right;
}
}
}
重建二叉树

1)先序遍历确定根的位置,再用中序遍历确定左右子树的节点个数;
2)可先用HashMap存储中序遍历数组中各个数字的位置信息;
3)递归的参数需要包含先序数组的范围[preStart, End],中序数组的范围[inStart, inEnd]。
public static TreeNode buildTree(int[] preorder, int[] inorder) {
if (preorder.length == 0) {
return null;
}
Map<Integer, Integer> indexMap = new HashMap<>();
for (int i = 0; i < inorder.length; i++) {
indexMap.put(inorder[i], i);
}
return reversion(preorder, 0, preorder.length - 1, 0, inorder.length - 1, indexMap);
}
public static TreeNode reversion(int[] preorder, int preStart, int preEnd, int inStart, int inEnd, Map<Integer, Integer> indexMap) {
if (preStart == preEnd) {
TreeNode root = new TreeNode(preorder[preStart]);
return root;
}
int rootValue = preorder[preStart];
TreeNode root = new TreeNode(rootValue);
// 中序数组确定左右子树的节点数目
int inMed = indexMap.get(rootValue);
int leftNodeCount = inMed - inStart;
if (leftNodeCount > 0) {
root.left = reversion(preorder, preStart + 1, preStart + leftNodeCount, inStart, inMed - 1, indexMap);
}
int rightNodeCount = inEnd - inMed;
if (rightNodeCount > 0) {
root.right = reversion(preorder, preStart + leftNodeCount + 1, preEnd, inMed + 1, inEnd, indexMap);
}
return root;
}
实现 Trie (前缀树)

Trie一般也叫字典树。参考下图:

这棵字典树可以看成是如下单词集合{banana, anana, nana, ana, na, a}构成的树。
1)构造TrieNode
由上图可以看出一个字典树节点的成员变量应该有:
- 所有儿子节点的链接:考虑到需要进行对所有儿子节点进行快速检索,并且每个节点最多有26个儿子节点,所以使用数组存储,数组下标对应26个字母,表示潜在的26个儿子。
- 是否是儿子节点,可以设置一个boolean值(或者类似图中所示,给每个节点添加一个额外的儿子节点,'$'符号,表示此节点是否是儿子节点)。这里使用前者。
节点的成员方法应该有:
- 构造方法
- 是否包含某个儿子节点
- 获取任意一个儿子节点
- 是否是儿子节点;以及设置儿子节点;
2)实现Trie类的三种方法
Trie树类似其他树,也有一个类成员变量root节点;
insert方法就是逐级添加儿子节点的过程,最后一个儿子节点设为End;
startwith方法就是逐级搜索儿子节点的过程;
search方法在startwith方法的基础上,判断最后一个儿子节点是否是End即可。
public class Trie {
public class TrieNode{
TrieNode[] links;
boolean isEnd;
public TrieNode(){
links = new TrieNode[26];
}
public boolean containsChild(char c){
return links[c - 'a'] != null;
}
public TrieNode getChild(char c){
return links[c - 'a'];
}
public void setChild(char c, TrieNode node){
links[c - 'a'] = node;
}
public boolean isEnd(){
return isEnd;
}
public void setEnd(){
isEnd = true;
}
}
TrieNode root;
/** Initialize your data structure here. */
public Trie() {
root = new TrieNode();
}
/** Inserts a word into the trie. */
public void insert(String word) {
TrieNode curr = root;
for(int i = 0; i < word.length(); i++){
char c = word.charAt(i);
if(!curr.containsChild(c)){
curr.setChild(c, new TrieNode());
}
curr = curr.getChild(c);
}
curr.setEnd();
}
/** Returns if the word is in the trie. */
public boolean search(String word) {
TrieNode curr = root;
for(int i = 0; i < word.length(); i++){
char c = word.charAt(i);
if(!curr.containsChild(c)){
return false;
}
curr = curr.getChild(c);
}
return curr.isEnd;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
TrieNode curr = root;
for(int i = 0; i < prefix.length(); i++){
char c = prefix.charAt(i);
if(!curr.containsChild(c)){
return false;
}
curr = curr.getChild(c);
}
return true;
}
}
另外一种构造TrieNode的方法:
字母的value存为一个字段,而不是像上面的方法表示在数组的索引中;
然后用HashMap保存所有儿子节点,实现O(1)的检索效率;
是否是End节点,通过在儿子节点中添加一个值为'$'的儿子即可;
此种方法更容易被自然的想到。
public class Trie {
public class TrieNode{
Character value;
Map<Character, TrieNode> childMap;
public TrieNode(){}
public TrieNode(Character value){
this.value = value;
}
}
private static final Character END = '$';
TrieNode root;
/** Initialize your data structure here. */
public Trie() {
root = new TrieNode();
}
/** Inserts a word into the trie. */
public void insert(String word) {
TrieNode curr = root;
for(int i = 0; i < word.length(); i++){
char c = word.charAt(i);
if(curr.childMap != null){
TrieNode child = curr.childMap.get(c);
if(child != null){
curr = child;
continue;
}
}
TrieNode newNode = new TrieNode(c);
curr.childMap = curr.childMap == null ? new HashMap<>() : curr.childMap;
curr.childMap.put(c, newNode);
curr = newNode;
}
// 插入结束符
curr.childMap = curr.childMap == null ? new HashMap<>() : curr.childMap;
curr.childMap.put(END, new TrieNode(END));
}
/** Returns if the word is in the trie. */
public boolean search(String word) {
TrieNode curr = root;
for(int i = 0; i < word.length(); i++){
char c = word.charAt(i);
if(curr != null && curr.childMap != null){
TrieNode node = curr.childMap.get(c);
if(node == null){
return false;
}
if(i == word.length() - 1 && node.childMap.containsKey(END)){
return true;
}
curr = node;
continue;
}
return false;
}
return false;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
TrieNode curr = root;
for(int i = 0; i < prefix.length(); i++){
char c = prefix.charAt(i);
if(curr != null && curr.childMap != null){
TrieNode node = curr.childMap.get(c);
if(node == null){
return false;
}
curr = node;
continue;
}
return false;
}
return true;
}
}
路径总和 II

public static List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> paths = new ArrayList<>();
if(root == null){
return paths;
}
List<Integer> path = new ArrayList<>();
path.add(root.val);
dfs(paths, path, sum, root.val, root);
return paths;
}
public static void dfs(List<List<Integer>> paths, List<Integer> path, int target, int sum, TreeNode root){
if(sum == target && root.left == null && root.right == null){
paths.add(new ArrayList<>(path));
return;
}
if(root.left != null){
sum += root.left.val;
path.add(root.left.val);
dfs(paths, path, target, sum, root.left);
sum -= root.left.val;
path.remove(path.size()-1);
}
if(root.right != null){
sum += root.right.val;
path.add(root.right.val);
dfs(paths, path, target, sum, root.right);
sum -= root.right.val;
path.remove(path.size()-1);
}
}
二叉树中和为某一值的路径

回溯
- 正向思维,记录当前路径的和;注意作为参数的变量,在回溯调用之前和之后必须保持一致,所以在添加path到ans的时候,将当前节点的值加入的是刚new出来的rightAns中,而不是先加入path,再付给rightAns。
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> ans = new ArrayList<>();
if(root == null){
return ans;
}
dfs(ans, new ArrayList<>(), root, 0, sum);
return ans;
}
public void dfs(List<List<Integer>> ans, List<Integer> path, TreeNode current, int pathSum, int sum){
if(pathSum + current.val == sum && current.left == null && current.right == null){
List<Integer> rightAns = new ArrayList<>(path);
rightAns.add(current.val);
ans.add(rightAns);
return;
}
if(current.left != null){
path.add(current.val);
dfs(ans, path, current.left, pathSum + current.val, sum);
path.remove(path.size()-1);
}
if(current.right != null){
path.add(current.val);
dfs(ans, path, current.right, pathSum + current.val, sum);
path.remove(path.size()-1);
}
}
- 逆向思维,记录剩下的路径值。
public void dfs(List<List<Integer>> ans, List<Integer> path, TreeNode current, int diff){
if(current == null){
return;
}
path.add(current.val);
diff -= current.val;
if(diff == 0 && current.left == null && current.right == null){
ans.add(new ArrayList<>(path));
}
dfs(ans, path, current.left, diff);
dfs(ans, path, current.right, diff);
path.remove(path.size()-1);
}
不同的二叉搜索树 II

递归

- 注意递归函数的结束条件,不能直接返回null,而是返回一个包含null元素的list。因为即使是叶子节点也应该有一个null的左子树和一个null的右子树。
public List<TreeNode> generateTrees(int n) {
if (n == 0) {
return new ArrayList<>();
}
return generateTrees(1, n);
}
public List<TreeNode> generateTrees(int start, int end) {
List<TreeNode> trees = new ArrayList<>();
if (start > end) {
trees.add(null);
return trees;
}
for (int i = start; i <= end; i++) {
List<TreeNode> leftTrees = generateTrees(start, i - 1);
List<TreeNode> rightTrees = generateTrees(i + 1, end);
for (TreeNode leftTree : leftTrees) {
for (TreeNode rightTree : rightTrees) {
TreeNode root = new TreeNode(i);
root.left = leftTree;
root.right = rightTree;
trees.add(root);
}
}
}
return trees;
}
36. 二叉搜索树与双向链表


树的旋转
参考树的旋转操作
public Node treeToDoublyList(Node root) {
if(root == null){
return null;
}
while (root.right != null){
root = rotateWithRightChild(root);
}
Node maxNode = root;
while (root.left != null){
while (root.left.right != null){
root.left = rotateWithRightChild(root.left);
}
root = root.left;
}
Node minNode = root;
// 二叉树搜索树:每个节点只有左节点
maxNode.right = minNode;
Node curr = maxNode;
Node last = curr;
while (curr != minNode){
curr = curr.left;
curr.right = last;
last = curr;
}
curr.left = maxNode;
return curr;
}
public Node rotateWithRightChild(Node root){
Node ret = root.right;
Node rightChild = root.right;
root.right = null;
while (rightChild.left != null){
rightChild = rightChild.left;
}
rightChild.left = root;
return ret;
}
中序遍历

class Solution {
Node pre, head;
public Node treeToDoublyList(Node root) {
if (root == null) {
return null;
}
dfs(root);
head.left = pre;
pre.right = head;
return head;
}
void dfs(Node cur) {
if (cur == null) {
return;
}
dfs(cur.left);
if (pre != null) {
pre.right = cur;
} else {
head = cur;
}
cur.left = pre;
pre = cur;
dfs(cur.right);
}
}
删除二叉搜索树中的节点


递归
1)一般而言返回的仍然是root节点,所以递归的形式为:
root.right = deleteNode(root.right, key);
root.left = deleteNode(root.left, key);
2)deleteNode返回删除对应节点后的子树的根;这里的删除,可以采用替换数字的方式;
两种做法:使用右子树的最小数代替,或者使用左子树的最大数代替;
注意替换数字后,还要递归删除替换的最小数/最大数。
public TreeNode deleteNode(TreeNode root, int key) {
if (root == null) {
return null;
}
if(root.val < key){
root.right = deleteNode(root.right, key);
}else if(root.val > key){
root.left = deleteNode(root.left, key);
}else {
TreeNode rightMin = root.right;
if(rightMin != null){
while (rightMin.left != null){
rightMin = rightMin.left;
}
root.val = rightMin.val;
root.right = deleteNode(root.right, rightMin.val); // 递归删除替换的数
return root;
} else {
return root.left;
}
}
return root;
}
完全二叉树的节点个数

二分法
1)用二分法判断最后一行的最后一个节点的顺序索引,最后一行的所有节点的索引必定在;
2)判断最后一行的某个索引节点是否存在,需要O(logN)复杂度;
总体复杂度为
public int countNodes(TreeNode root) {
if(root == null){
return 0;
}
int level = 0;
TreeNode ptr = root;
while (ptr.left != null){
level++;
ptr = ptr.left;
}
int min = 1;
int max = (int) Math.pow(2, level);
int lastIndex = 1;
while (min <= max){
int med = (min + max) / 2;
if(exist(root, med, level)){
lastIndex = med;
min = med + 1;
}else {
max = med - 1;
}
}
int count = (int) Math.pow(2, level) - 1 + lastIndex;
return count;
}
public boolean exist(TreeNode root, int index, int level){
TreeNode ptr = root;
int min = 1;
int max = (int) Math.pow(2, level);
for(int i=0; i<level; i++){
int med = (min + max) / 2;
if(index > med){
min = med + 1;
ptr = ptr.right;
}else {
ptr = ptr.left;
max = med;
}
}
return ptr != null;
}
二叉树的完全性检验


广度优先遍历:层序遍历

public boolean isCompleteTree(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<>();
TreeNode prev = root;
queue.add(root);
while (!queue.isEmpty()) {
TreeNode node = queue.remove();
if (prev == null && node != null)
return false;
if (node != null) {
queue.add(node.left);
queue.add(node.right);
}
prev = node;
}
return true;
}
另一种思路:按层遍历节点,判断每一个节点:
1)是否能有儿子节点
2)是否有左儿子却没右儿子
在遍历每一层的节点时,需要根据下一层的儿子节点做判断
public boolean isCompleteTree(TreeNode root) {
if (root == null) {
return true;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
int level = 0;
boolean couldHasChild = true;
while (!queue.isEmpty()) {
int size = queue.size();
if (size < (int) Math.pow(2, level++)) {
couldHasChild = false;
}
for (int i = 0; i < size; i++) {
TreeNode current = queue.poll();
if (current.left == null && current.right != null) {
return false;
}
if (!couldHasChild && hasChild(current)) {
return false;
}
if (current.left != null) {
queue.add(current.left);
}
if (current.right != null) {
queue.add(current.right);
}
if(current.left == null || current.right == null){
couldHasChild = false;
}
}
}
return true;
}
public boolean hasChild(TreeNode node) {
return node.left != null || node.right != null;
}
序列化和反序列化二叉搜索树

后续遍历

public class Codec {
public String serialize(TreeNode root) {
StringBuilder stringBuilder = new StringBuilder();
postReverse(root, stringBuilder);
return stringBuilder.toString().trim();
}
public String postReverse(TreeNode node, StringBuilder sb) {
if (node == null) {
return sb.toString();
}
postReverse(node.left, sb);
postReverse(node.right, sb);
sb.append(node.val);
sb.append(" ");
return sb.toString();
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
if("".equalsIgnoreCase(data)){
return null;
}
String[] strings = data.split("\\s+");
int[] nums = new int[strings.length];
for (int i = 0; i < strings.length; i++) {
nums[i] = Integer.parseInt(strings[i]);
}
return recover(nums, 0, nums.length - 1);
}
public TreeNode recover(int[] nums, int left, int right) {
if (left > right) {
return null;
}
int value = nums[right];
TreeNode node = new TreeNode(value);
int med = left;
while (med < right && nums[med] < value) {
med++;
}
node.left = recover(nums, left, med - 1);
node.right = recover(nums, med, right - 1);
return node;
}
}
- 对于上述寻找左子树和右子树的分界点,这一步骤其实没有必要,后续遍历为“左,右,根”,取完末尾元素构建根节点之后,之前的相邻元素就是右子树,紧接着构建右子树,每构建一个节点,就remove掉,等到右子树构建完,自然就轮到左子树的节点了,只要给一个子树的取值范围即可。
public TreeNode deserialize(String data) {
if("".equalsIgnoreCase(data)){
return null;
}
String[] strings = data.split("\\s+");
ArrayList<Integer> nums = new ArrayList<>();
for (int i = 0; i < strings.length; i++) {
nums.add(Integer.parseInt(strings[i]));
}
return recover(nums, Integer.MIN_VALUE, Integer.MAX_VALUE);
}
public TreeNode recover(ArrayList<Integer> nums , int min, int max) {
if (nums.size() == 0) {
return null;
}
int value = nums.get(nums.size()-1); // 取根节点
if(value < min || value > max){ // 判断节点是不是在对应的范围内
return null;
}
nums.remove(nums.size()-1); // 移除节点
TreeNode node = new TreeNode(value);
node.right = recover(nums, value, max); // 构建右子树必须在前
node.left = recover(nums, min, value); // 构建左子树必须在后
return node;
}
二叉搜索树中第K小的元素

递归-中序遍历
public ArrayList<Integer> inorder(TreeNode root, ArrayList<Integer> arr) {
if (root == null) return arr;
inorder(root.left, arr);
arr.add(root.val);
inorder(root.right, arr);
return arr;
}
public int kthSmallest(TreeNode root, int k) {
ArrayList<Integer> nums = inorder(root, new ArrayList<Integer>());
return nums.get(k - 1);
}
迭代-中序遍历
public int kthSmallest(TreeNode root, int k) {
Stack<TreeNode> stack = new Stack<>();
TreeNode current = root;
while (current != null || !stack.isEmpty()){
while (current != null){
stack.push(current);
current = current.left;
}
current = stack.pop();
if(k == 1){
return current.val;
}
k--;
current = current.right;
}
return -1;
}
从中序与后序遍历序列构造二叉树

递归
- 注意使用map存储inorder的数值和下标的映射关系
// 左 根 右
// 左 右 根
private Map<Integer, Integer> index;
public TreeNode buildTree(int[] inorder, int[] postorder) {
index = new HashMap<>();
int n = inorder.length;
for (int i = 0; i < n; i++) {
index.put(inorder[i], i);
}
return buildTree(inorder, 0, n - 1, postorder, 0, n - 1);
}
public TreeNode buildTree(int[] inorder, int left, int right, int[] postorder, int L, int R) {
if (left > right || L > R) {
return null;
}
TreeNode root = new TreeNode(postorder[R]);
int med = index.get(postorder[R]);
// right - left = R - L
root.left = buildTree(inorder, left, med - 1, postorder, L, L + med - 1 - left);
root.right = buildTree(inorder, med + 1, right, postorder, R - right + med, R - 1);
return root;
}
单词的压缩编码


存储单词后缀
public int minimumLengthEncoding(String[] words) {
Set<String> good = new HashSet(Arrays.asList(words));
for (String word: words) {
for (int k = 1; k < word.length(); ++k)
good.remove(word.substring(k));
}
int ans = 0;
for (String word: good)
ans += word.length() + 1;
return ans;
}
字典树
去找到是否不同的单词具有相同的后缀,我们可以将其反序之后插入字典树中。例如,我们有 "time" 和 "me",可以将 "emit" 和 "em" 插入字典树中。
- 反序加入单词到trie中,即add方法
- 字典树节点:TrieNode类,维护所有儿子节点(数组、HashMap),及是否是叶子节点
- 返回所有叶子节点的"高度+1"的和,即getCount方法
public int minimumLengthEncoding(String[] words) {
Trie trie = new Trie();
for(String word : words){
trie.add(word);
}
int ans = trie.getCount();
return ans;
}
class Trie {
TrieNode root;
public Trie() {
root = new TrieNode(true);
}
public void add(String word) {
TrieNode ptr = root;
for (int i = word.length() - 1; i >= 0; i--) {
int index = word.charAt(i) - 'a';
if (ptr.child[index] == null) {
ptr.child[index] = new TrieNode(true); // 添加孩子
ptr.isLeaf = false;
}
ptr = ptr.child[index];
}
}
public int getCount(){
return getCount(root, 0);
}
public int getCount(TrieNode node, int height) {
if(node == null){
return 0;
}
if (node.isLeaf) {
return height + 1;
}
int total = 0;
for (TrieNode trieNode : node.child) {
total += getCount(trieNode, height + 1);
}
return total;
}
}
class TrieNode {
TrieNode[] child = new TrieNode[26];
boolean isLeaf;
public TrieNode(boolean isLeaf) {
this.isLeaf = isLeaf;
}
}
优化
上面的代码中,获取所有叶子节点时,通过从遍历字典树得到,其实在加入word的时候,可以用一个HashMap将每个word对应的末尾节点存储下来,这样通过遍历HashMap,就可以得到所有的叶子节点,同时对应word的length就是叶子节点的高度。
public int minimumLengthEncoding(String[] words) {
Trie trie = new Trie();
for(String word : words){
trie.add(word);
}
int ans = trie.getCount();
return ans;
}
class Trie {
TrieNode root;
HashMap<TrieNode, String> leafWordMap;
public Trie() {
root = new TrieNode(true);
leafWordMap = new HashMap<>();
}
public void add(String word) {
TrieNode ptr = root;
for (int i = word.length() - 1; i >= 0; i--) {
int index = word.charAt(i) - 'a';
if (ptr.child[index] == null) {
ptr.child[index] = new TrieNode(true); // 添加孩子
ptr.isLeaf = false;
}
ptr = ptr.child[index];
}
leafWordMap.put(ptr, word); // 潜在的叶子节点
}
public int getCount(){
int count = 0;
for(TrieNode trieNode : leafWordMap.keySet()){
if(trieNode.isLeaf){
count += leafWordMap.get(trieNode).length() + 1;
}
}
return count;
}
}
class TrieNode {
TrieNode[] child = new TrieNode[26];
boolean isLeaf;
public TrieNode(boolean isLeaf) {
this.isLeaf = isLeaf;
}
}
二叉树中所有距离为 K 的结点

递归

public class Solution {
public static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
private List<Integer> ans;
private TreeNode target;
private int K;
public List<Integer> distanceK(TreeNode root, TreeNode target, int K) {
ans = new LinkedList();
this.target = target;
this.K = K;
dfs(root);
return ans;
}
// 返回当前节点与target节点的之间的路径上的节点数(即当前节点与target节点之间的距离+1); 如果路径不存在, 返回-1;
public int dfs(TreeNode node) {
if (node == null)
return -1;
else if (node == target) {
subtree_add(node, 0);
return 1;
} else {
int L = dfs(node.left);
int R = dfs(node.right);
if (L != -1) {
if (L == K) {
ans.add(node.val);
}
subtree_add(node.right, L + 1);
return L + 1;
} else if (R != -1) {
if (R == K) {
ans.add(node.val);
}
subtree_add(node.left, R + 1);
return R + 1;
} else {
return -1;
}
}
}
// 添加node节点以下与node节点距离为K-dist的节点
public void subtree_add(TreeNode node, int dist) {
if (node == null || dist > K)
return;
if (dist == K)
ans.add(node.val);
else {
subtree_add(node.left, dist + 1);
subtree_add(node.right, dist + 1);
}
}
}
添加父指针+双队列
- 将每个节点的父节点存储在HashMap中
- 从target节点开始遍历,将节点入队列的同时,将对应的distance也入队列。节点队列和距离队列必须同步操作,同时出栈和入栈,即可得到节点的同时得到其对应的距离。当节点的距离为0时,是我们需要的答案;对于每个节点判断完毕之后,加入其父节点,左节点和右节点,同时其距离减1。
- 用HashSet保存访问过的节点;
public class Solution {
public static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
private Map<TreeNode, TreeNode> parentMap;
private HashSet<TreeNode> visited;
public List<Integer> distanceK(TreeNode root, TreeNode target, int K) {
List<Integer> ans = new ArrayList<>();
if (K == 0) {
ans.add(target.val);
return ans;
}
parentMap = new HashMap();
visited = new HashSet<>();
// 获取所有节点的父节点
dfs(root, null);
// 从target节点开始遍历
Queue<TreeNode> nodeQueue = new LinkedList();
Queue<Integer> distQueue = new LinkedList<>();
nodeQueue.add(target);
distQueue.add(K);
while (!nodeQueue.isEmpty()) {
TreeNode currentNode = nodeQueue.poll();
int dist = distQueue.poll();
if (!visited.contains(currentNode)) {
visited.add(currentNode);
if (dist == 0) {
ans.add(currentNode.val);
} else {
// 添加父节点
TreeNode parent = parentMap.get(currentNode);
if (parent != null && !visited.contains(parent)) {
nodeQueue.add(parent);
distQueue.add(dist - 1);
}
// 添加左节点或者右节点
if (currentNode.left != null && !visited.contains(currentNode.left)) {
nodeQueue.add(currentNode.left);
distQueue.add(dist - 1);
}
if (currentNode.right != null && !visited.contains(currentNode.right)) {
nodeQueue.add(currentNode.right);
distQueue.add(dist - 1);
}
}
}
}
return ans;
}
public void dfs(TreeNode node, TreeNode par) {
if (node != null) {
parentMap.put(node, par);
dfs(node.left, node);
dfs(node.right, node);
}
}
}