2021-07-09算法题

135 阅读1分钟
  1. 对称二叉树

image.png 思路:在判断两棵树是否相同的算法的基础上稍加修改即可

class Solution {
    public boolean isSymmetric(TreeNode root) {
        if (root == null) {
            return true;
        }
        return isSameTree(root.left, root.right);
    }

    public boolean isSameTree(TreeNode p, TreeNode q) {
        if (p == null && q == null) {
            return true;
        } else if (p == null || q == null) {
            return false;
        } else if (p.val != q.val) {
            return false;
        } else {
            return isSameTree(p.left, q.right) && isSameTree(p.right, q.left);//修改处
        }
    }
}
  1. 二叉树的最大深度

image.png 思路:如果我们知道了左子树和右子树的最大深度lDepth和rDepth,那么该二叉树的最大深度即为max(lDepth,rDepth)+1。而左子树和右子树的最大深度又可以以同样的方式进行计算。因此我们可以用「深度优先搜索」的方法来计算二叉树的最大深度。具体而言,在计算当前二叉树的最大深度时,可以先递归计算出其左子树和右子树的最大深度,然后在O(1) 时间内计算出当前二叉树的最大深度。

class Solution {
    public int maxDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int lDepth = maxDepth(root.left);
        int rDepth = maxDepth(root.right);
        return lDepth > rDepth ? lDepth + 1 : rDepth + 1;
    }
}
  1. 将有序数组转换为二叉搜索树

image.png 思路: