LeetCode 必刷题目集合-树

普通二叉树

94.二叉树的中序遍历

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    List<Integer> res = new ArrayList<>();
    // 递归
    // public List<Integer> inorderTraversal(TreeNode root) {
    //     if (root == null) return res;
    //     inorder(root);
    //     return res;
    // }

    // public void inorder(TreeNode root) {
    //     if (root == null) return;
    //     inorder(root.left);
    //     res.add(root.val);
    //     inorder(root.right);
    // }

    // 迭代
    public List<Integer> inorderTraversal(TreeNode root) {
        if (root == null) return res;
        Stack<TreeNode> stack = new Stack<>();
        while (root != null || !stack.isEmpty()) {
            while (root != null) {
                stack.push(root);
                root = root.left;
            }
            root = stack.pop();
            res.add(root.val);
            root = root.right;
        }
        return res;
    }
}

144.二叉树的前序遍历

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    List<Integer> res = new ArrayList<>();

    // 递归
    // public List<Integer> preorderTraversal(TreeNode root) {
    //     if (root == null) return res;
    //     preorder(root);
    //     return res;
    // }

    // public void preorder(TreeNode root) {
    //     if (root == null) return;
    //     res.add(root.val);
    //     preorder(root.left);
    //     preorder(root.right);
    // }

    // 迭代
    public List<Integer> preorderTraversal(TreeNode root) {
        if (root == null) return res;
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        while (!stack.isEmpty()) {
            root = stack.pop();
            res.add(root.val);
            if (root.right != null) stack.push(root.right);
            if (root.left != null) stack.push(root.left);
        }
        return res;
    }
}

145.二叉树的后序遍历

在这里插入图片描述

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    List<Integer> res = new ArrayList<>();
    // 递归
    // public List<Integer> postorderTraversal(TreeNode root) {
    //     if (root == null) return res;
    //     postorder(root);
    //     return res;
    // }

    // public void postorder(TreeNode root) {
    //     if (root == null) return;
    //     postorder(root.left);
    //     postorder(root.right);
    //     res.add(root.val);
    // }

    // 迭代
    // 前序遍历:根 - 左 - 右
    // 后序遍历:左 - 右 - 根
    // 将前序遍历左右互换,即得到后序遍历的逆序:根 - 右 - 左
    public List<Integer> postorderTraversal(TreeNode root) {
        if (root == null) return res;
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        while (!stack.isEmpty()) {
            root = stack.pop();
            res.add(root.val);
            if (root.left != null) stack.push(root.left);
            if (root.right != null) stack.push(root.right);
        }
        Collections.reverse(res);
        return res;
    }

104.二叉树的最大深度

在这里插入图片描述

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public int maxDepth(TreeNode root) {
        if (root == null) return 0;
        return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
    }
}

111.二叉树的最小深度

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
	// 注意:不用于求最大深度直接递归
    // 最小深度需要分别计算左右子节点为 null 的情况,因为题目所述:最小深度是从根节点到最近叶子节点的最短路径上的节点数量
    public int minDepth(TreeNode root) {
        if (root == null) return 0;
        if (root.left == null) return minDepth(root.right) + 1;
        else if (root.right == null) return minDepth(root.left) + 1;
        else return Math.min(minDepth(root.left), minDepth(root.right)) + 1;
    }
}

226.翻转二叉树

在这里插入图片描述

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public TreeNode invertTree(TreeNode root) {
        if (root == null) return root;
        TreeNode left = invertTree(root.left);
        TreeNode right = invertTree(root.right);
        root.left = right;
        root.right = left;
        return root;
    }
}

101.对称二叉树

在这里插入图片描述
在这里插入图片描述

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    // 方法1:递归
    // public boolean isSymmetric(TreeNode root) {
    //     return recursion(root.left, root.right);
    // }

    // public boolean recursion(TreeNode nodeL, TreeNode nodeR) {
    //     // 判断 2 个节点是否都为 null
    //     if (nodeL == nodeR) return true;
    //     // 判断 2 个节点是否其中有 1 个节点为 null
    //     else if (nodeL != nodeR && (nodeL == null || nodeR == null)) return false;
    //     // 2 个节点都不为 null,判断值是否相等,同时向下递归
    //     return nodeL.val == nodeR.val && recursion(nodeL.left, nodeR.right) && recursion(nodeL.right, nodeR.left);
    // }

    // 方法2:迭代,使用 2 个队列分别保存左右子树的节点
    public boolean isSymmetric(TreeNode root) {
        Queue<TreeNode> queueL = new LinkedList<>();
        Queue<TreeNode> queueR = new LinkedList<>();
        queueL.offer(root.left);
        queueR.offer(root.right);
        while (!queueL.isEmpty() && !queueR.isEmpty()) {
            TreeNode nodeL = queueL.poll();
            TreeNode nodeR = queueR.poll();
            if (nodeL == nodeR) continue;
            else if (nodeL != nodeR && (nodeL == null || nodeR == null)) return false;
            else {
                if (nodeL.val != nodeR.val) return false;
                queueL.offer(nodeL.left);
                queueL.offer(nodeL.right);
                queueR.offer(nodeR.right);
                queueR.offer(nodeR.left);
            }
        }
        return queueL.isEmpty() && queueR.isEmpty();
    }
}

617.合并二叉树

在这里插入图片描述

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    // 方法1:递归
    public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
        if (root1 == null) return root2;
        else if (root2 == null) return root1;
        root1.val += root2.val;
        root1.left = mergeTrees(root1.left, root2.left);
        root1.right = mergeTrees(root1.right, root2.right); 
        return root1;
    }

    // 方法2:迭代
    // public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
    //     if (root1 == null) return root2;
    //     else if (root2 == null) return root1;
    //     Queue<TreeNode> queue1 = new LinkedList<>();
    //     Queue<TreeNode> queue2 = new LinkedList<>();
    //     queue1.offer(root1);
    //     queue2.offer(root2);
    //     while (!queue1.isEmpty() && !queue2.isEmpty()) {
    //         TreeNode node1 = queue1.poll();
    //         TreeNode node2 = queue2.poll();
    //         node1.val += node2.val;
    //         if (node1.left != null && node2.left != null) {
    //             queue1.offer(node1.left);
    //             queue2.offer(node2.left);
    //         } else if (node1.left == null) node1.left = node2.left;
    //         if (node1.right != null && node2.right != null) {
    //             queue1.offer(node1.right);
    //             queue2.offer(node2.right);
    //         } else if (node1.right == null) node1.right = node2.right;
    //     }
    //     return root1;
    // }
}

112.路径总和

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public boolean hasPathSum(TreeNode root, int targetSum) {
        if (root == null) return false;
        if (root.left == null && root.right == null && root.val == targetSum) return true;
        targetSum -= root.val;
        return hasPathSum(root.left, targetSum) || hasPathSum(root.right, targetSum);
    }
}

113.路径总和 II

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    List<List<Integer>> res = new ArrayList<>();
    List<Integer> list = new ArrayList<>();

    public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
        if (root == null) return res;
        backTracking(root, 0, targetSum);
        return res;
    }

    public void backTracking(TreeNode root, int sum, int targetSum) {
        if (root == null) return;
        list.add(root.val);
        sum += root.val;
        if (root.left == null && root.right == null && sum == targetSum) res.add(new ArrayList<>(list));
        backTracking(root.left, sum, targetSum);
        backTracking(root.right, sum, targetSum);
        list.remove(list.size() - 1);
    }
}

437.路径总和 III

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    // 双重递归
    public int pathSum(TreeNode root, int targetSum) {
        if (root == null) return 0;
        return getSum(root, targetSum) + pathSum(root.left, targetSum) + pathSum(root.right, targetSum);
    }

    // 计算从当前节点开始的满足条件的路径数目
    public int getSum(TreeNode root, int targetSum) {
        int count = 0;
        if (root == null) return 0;
        targetSum -= root.val;
        if (targetSum == 0) count = 1;
        return count + getSum(root.left, targetSum) + getSum(root.right, targetSum);
    }
}

572.另一颗树的子树

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public boolean isSubtree(TreeNode root, TreeNode subRoot) {
        if (root == null) return false;
        return helper(root, subRoot) || isSubtree(root.left, subRoot) || isSubtree(root.right, subRoot);
    }

    public boolean helper(TreeNode root, TreeNode subRoot) {
        if (root == null && subRoot == null) return true;
        if (root == null || subRoot == null) return false;
        if (root.val != subRoot.val) return false;
        return helper(root.left, subRoot.left) && helper(root.right, subRoot.right);
    }
}

404.左叶子之和

在这里插入图片描述

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    private int sum = 0;
    public int sumOfLeftLeaves(TreeNode root) {
        if (root == null) return 0;
        helper(root, root);
        return sum;
    }

    public void helper(TreeNode root, TreeNode parent) {
        if (root == null) return;
        if (root.left == null && root.right == null && parent.left == root) sum += root.val;
        helper(root.left, root);
        helper(root.right, root);
    }
}

671.二叉树中第二小的节点

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public int findSecondMinimumValue(TreeNode root) {
        // 子节点个数只能为 2 或 0,所以可以判断当前节点是否有子节点
        if (root == null || root.left == null) return -1;
        int left = (root.val == root.left.val ? findSecondMinimumValue(root.left) : root.left.val);
        int right = (root.val == root.right.val ? findSecondMinimumValue(root.right) : root.right.val);
        if (left == -1) return right;
        if (right == -1) return left;
        return Math.min(left, right);
    }
}

105.从前序与中序遍历序列构造二叉树

在这里插入图片描述
在这里插入图片描述

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    int[] preorder;
    int[] inorder;
    // 题意说明:inorder 中无重复元素,因此可以使用 Map 来存储以实现 O(1) 快速查找对应元素下标
    Map<Integer, Integer> map;

    public TreeNode buildTree(int[] preorder, int[] inorder) {
        this.preorder = preorder;
        this.inorder = inorder;
        map = new HashMap<>();
        for (int i = 0; i < inorder.length; i++) map.put(inorder[i], i);
        return buildTree(0, 0, inorder.length - 1);
    }

    // indexP:当前树的根节点在 preorder 中的下标
    // leftI:当前树的左边界
    // rightI:当前树的右边界
    // indexI:当前树的根节点在 inorder 中的下标
    public TreeNode buildTree(int indexP, int leftI, int rightI) {
        if (leftI > rightI) return null;
        TreeNode root = new TreeNode(preorder[indexP]);
        if (leftI == rightI) return root;
        int indexI = map.get(preorder[indexP]);
        root.left = buildTree(indexP + 1, leftI, indexI - 1);
        root.right = buildTree(indexP + indexI - leftI + 1, indexI + 1, rightI);
        return root;
    }
}

106.从中序与后序遍历序列构造二叉树

在这里插入图片描述

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    int[] inorder;
    int[] postorder;
    Map<Integer, Integer> map;

    public TreeNode buildTree(int[] inorder, int[] postorder) {
        this.inorder = inorder;
        this.postorder = postorder;
        map = new HashMap<>();
        for (int i = 0; i < inorder.length; i++) map.put(inorder[i], i);
        return buildTree(postorder.length - 1, 0, inorder.length - 1);
    }

    public TreeNode buildTree(int indexP, int leftI, int rightI) {
        if (leftI > rightI) return null;
        TreeNode root = new TreeNode(postorder[indexP]);
        if (leftI == rightI) return root;
        int indexI = map.get(postorder[indexP]);
        root.left = buildTree(indexP - 1 - (rightI - indexI), leftI, indexI - 1);
        root.right = buildTree(indexP - 1, indexI + 1, rightI);
        return root;
    }
}

BST 二叉搜索树

669.修剪二叉搜索树

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public TreeNode trimBST(TreeNode root, int low, int high) {
        if (root == null) return null;
        if (root.val < low) return trimBST(root.right, low, high);
        if (root.val > high) return trimBST(root.left, low, high);
        root.left = trimBST(root.left, low, high);
        root.right = trimBST(root.right, low, high);
        return root;
    }
}

230.二叉搜索树中第 k 小的元素

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    private int index = 0;
    private int result = 0;
    public int kthSmallest(TreeNode root, int k) {
        inorder(root, k);
        return result;
    }

    public void inorder(TreeNode root, int k) {
        if (root == null) return;
        inorder(root.left, k);
        if (++index == k) {
            result = root.val;
            return;
        }
        inorder(root.right, k);
    }
}

538.把二叉搜索树转换成累加树

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    private int sum = 0;
    public TreeNode convertBST(TreeNode root) {
        if (root == null) return null;
        convertBST(root.right);
        sum += root.val;
        root.val = sum;
        convertBST(root.left);
        return root;
    }
}

剑指 Offer 68 - I.二叉搜索树的最近公共祖先

在这里插入图片描述
在这里插入图片描述

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (p.val > q.val) {
            TreeNode temp = p;
            p = q;
            q = temp;
        }
        if (q.val < root.val) return lowestCommonAncestor(root.left, p, q);
        if (p.val > root.val) return lowestCommonAncestor(root.right, p, q);
        return root;
    }
}

剑指 Offer 68 - II.二叉搜索树的最近公共祖先

在这里插入图片描述
在这里插入图片描述

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null) return null;
        if (root == p || root == q) return root;
        TreeNode left = lowestCommonAncestor(root.left, p, q);
        TreeNode right = lowestCommonAncestor(root.right, p, q);
        if (left == null) return right;
        if (right == null) return left;
        return root;
    }
}

98.验证二叉搜索树

在这里插入图片描述
在这里插入图片描述

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    long min = Long.MIN_VALUE;
    long max = Long.MAX_VALUE;

    public boolean isValidBST(TreeNode root) {
        return isValidBST(root, min, max);
    }

    public boolean isValidBST(TreeNode root, long min, long max) {
        if (root == null) return true;
        if (root.val <= min || root.val >= max) return false;
        return isValidBST(root.left, min, root.val) && isValidBST(root.right, root.val, max);
    }
}

653.两数之和 IV - 输入 BST

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    // private Set<Integer> set = new HashSet<>();
    private List<Integer> list = new ArrayList<>();
    public boolean findTarget(TreeNode root, int k) {
        // if (root == null) return false;
        // if (!set.contains(k - root.val)) set.add(root.val);
        // else return true;
        // return findTarget(root.left, k) || findTarget(root.right, k);

        inorder(root);
        int left = 0;
        int right = list.size() - 1;
        while (left < right) {
            int sum = list.get(left) + list.get(right);
            if (sum > k) right--;
            else if (sum < k) left++;
            else return true;
        }
        return false;
    }

    public void inorder(TreeNode root) {
        if (root == null) return;
        inorder(root.left);
        list.add(root.val);
        inorder(root.right);
    }
}

530.二叉搜索树的最小绝对差

在这里插入图片描述
在这里插入图片描述

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    private int min = Integer.MAX_VALUE;
    private int pre = -1;

    public int getMinimumDifference(TreeNode root) {
        preorder(root);
        return min;
    }

    public void preorder(TreeNode root) {
        if (root == null) return;
        preorder(root.left);
        if (pre != -1) min = Math.min(min, root.val - pre);
        pre = root.val;
        preorder(root.right);
    }
}

501.二叉搜索树中的众数

在这里插入图片描述

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    private List<Integer> list = new ArrayList<>();
    private int maxCount = 1;
    private int curCount = 0;
    private Integer pre = null;

    public int[] findMode(TreeNode root) {
		// 采用中序遍历,val 相同的节点会相邻排列在一起
        inorder(root);
        int[] res = new int[list.size()];
        for (int i = 0; i < list.size(); i++) {
            res[i] = list.get(i);
        }
        return res;
    }

    public void inorder(TreeNode root) {
        if (root == null) return;
        inorder(root.left);
        helper(root.val);
        inorder(root.right);
    }

    public void helper(int x) {
        if (pre == null) {
            pre = x;
        }
        if (x == pre) curCount++;
        else {
            pre = x;
            curCount = 1;
        }
        if (curCount == maxCount) list.add(x);
        if (curCount > maxCount) {
            maxCount = curCount;
            list.clear();
            list.add(x);
        }

    }
}

平衡二叉树

110.平衡二叉树

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public boolean isBalanced(TreeNode root) {
        if (root == null) return true;
        return Math.abs(depth(root.left) - depth(root.right)) < 2 && isBalanced(root.left) && isBalanced(root.right);
    }

    public int depth(TreeNode root) {
        if (root == null) return 0;
        return Math.max(depth(root.left), depth(root.right)) + 1;
    }
}

AVL 平衡二叉搜索树

108.将有序数组转换为二叉搜索树

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public TreeNode sortedArrayToBST(int[] nums) {
        return helper(nums, 0, nums.length - 1);
    }

    public TreeNode helper(int[] nums, int left, int right) {
        if (left > right) return null;
        int mid = (left + right) / 2;
        TreeNode root = new TreeNode(nums[mid]);
        root.left = helper(nums, left, mid - 1);
        root.right = helper(nums, mid + 1, right);
        return root;
    }
}

109.有序链表转二叉搜索树

在这里插入图片描述

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public TreeNode sortedListToBST(ListNode head) {
        if (head == null) return null;
        if (head.next == null) return new TreeNode(head.val);
        ListNode pre = helper(head);
        ListNode next = pre.next.next;
        TreeNode root = new TreeNode(pre.next.val);
        pre.next = null;
        root.left = sortedListToBST(head);
        root.right = sortedListToBST(next);
        return root;
    }

    public ListNode helper(ListNode head) {
        ListNode pre = head;
        ListNode slow = head;
        ListNode fast = head;
        while (fast != null && fast.next != null) {
            pre = slow;
            slow = slow.next;
            fast = fast.next.next;
        }
        return pre;
    }

}

完全二叉树

958.二叉树的完全性检验

在这里插入图片描述
在这里插入图片描述

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public boolean isCompleteTree(TreeNode root) {
        // 层序遍历:当出现 null 节点时,后面不能再出现非 null 节点
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        boolean isEnd = false;
        while (!queue.isEmpty()) {
            TreeNode node = queue.poll();
            if (isEnd && node != null) return false;
            if (node == null) {
                isEnd = true;
                continue;
            }
            queue.offer(node.left);
            queue.offer(node.right);
        }
        return true;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值