- 平衡二叉树(*)
思路:利用平衡二叉树的定义:左右子树高度之差的绝对值不超过1且左右子树均为平衡二叉树
class Solution {
public boolean isBalanced(TreeNode root) {
if (root == null) {
return true;
}
return (Math.abs(getHeight(root.left) - getHeight(root.right)) <= 1) && isBalanced(root.left) && isBalanced(root.right);
}
public int getHeight(TreeNode root) {
if (root == null) {
return 0;
}
int lDepth = getHeight(root.left);
int rDepth = getHeight(root.right);
return Math.max(lDepth, rDepth) + 1;
}
}
- 二叉树的最小深度(*)
思路:创建新的结点,为其添加depth属性。进行广度遍历,当遇到叶结点时,返回该结点的depth。由于是广度遍历,所以此时返回的必定是最小的深度。
class Solution {
class BtNode {
TreeNode t;
int depth;
public BtNode(TreeNode root, int depth) {
t = root;
this.depth = depth;
}
}
public int minDepth(TreeNode root) {
if (root == null) {
return 0;
}
BtNode bt = new BtNode(root, 1);
Queue<BtNode> queue = new LinkedList<BtNode>();
queue.add(bt);
int depth = 0;
while (!queue.isEmpty()) {
depth = queue.peek().depth;
BtNode tt = queue.poll();
if (tt.t.left == null && tt.t.right == null) {
return tt.depth;
}
if (tt.t.left != null) {
queue.add(new BtNode(tt.t.left, depth + 1));
}
if (tt.t.right != null) {
queue.add(new BtNode(tt.t.right, depth + 1));
}
}
return 0;
}
}
其他思路:
- 路径总和(*)
思路:观察要求我们完成的函数,我们可以归纳出它的功能:询问是否存在从当前节点 root 到叶子节点的路径,满足其路径和为 sum。假定从根节点到当前节点的值之和为 val,我们可以将这个大问题转化为一个小问题:是否存在从当前节点的子节点到叶子的路径,满足其路径和为 sum - val。不难发现这满足递归的性质,若当前节点就是叶子节点,那么我们直接判断 sum 是否等于 val 即可
class Solution {
public boolean hasPathSum(TreeNode root, int targetSum) {
if (root == null) {
return false;
}
if (root.left == null && root.right == null) {
return targetSum == root.val;
}
return hasPathSum(root.left, targetSum - root.val) || hasPathSum(root.right, targetSum - root.val);
}
}