博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

笔试02

Posted on 2019-09-23 15:11  心默默言  阅读(144)  评论(0编辑  收藏  举报

1.求二叉树的深度

https://www.cnblogs.com/xudong-bupt/p/4036190.html

class TreeNode {
    char val;
    TreeNode left = null;
    TreeNode right = null;

    TreeNode(char _val) {
        this.val = _val;
    }
}

这个可以使用递归,分别求出左子树的深度、右子树的深度,两个深度的较大值+1即可。

// 获取最大深度
    public static int getMaxDepth(TreeNode root) {
        if (root == null)
            return 0;
        else {
            int left = getMaxDepth(root.left);
            int right = getMaxDepth(root.right);
            return 1 + Math.max(left, right);
        }
    }

2.二叉树宽度

  使用队列,层次遍历二叉树。在上一层遍历完成后,下一层的所有节点已经放到队列中,此时队列中的元素个数就是下一层的宽度。以此类推,依次遍历下一层即可求出二叉树的最大宽度。

// 获取最大宽度
    public static int getMaxWidth(TreeNode root) {
        if (root == null)
            return 0;

        Queue<TreeNode> queue = new ArrayDeque<TreeNode>();
        int maxWitdth = 1; // 最大宽度
        queue.add(root); // 入队

        while (true) {
            int len = queue.size(); // 当前层的节点个数
            if (len == 0)
                break;
            while (len > 0) {// 如果当前层,还有节点
                TreeNode t = queue.poll();
                len--;
                if (t.left != null)
                    queue.add(t.left); // 下一层节点入队
                if (t.right != null)
                    queue.add(t.right);// 下一层节点入队
            }
            maxWitdth = Math.max(maxWitdth, queue.size());
        }
        return maxWitdth;
    }

3.求一个二叉树是否为平衡树

    /
     * 求树的深度
     * @param root
     * @return
     */
    public static int TreeDepth(BinaryTreeNode root){
        if(root == null) {
            return 0;
        }
        int left = TreeDepth(root.left);
        int right = TreeDepth(root.right);
        return (left > right) ? (left+1) : (right+1);
    }
    /**
     * 一般解法
     * @param root
     * @return
     */
    public static boolean isBalanced(BinaryTreeNode root){
        if(root == null) {
            return true;
        }
        int left = TreeDepth(root.left);
        int right = TreeDepth(root.right);
        int diff = left-right;
        if(diff > 1 || diff < -1){
            return false;
        }
        return isBalanced(root.left) && isBalanced(root.right);
    }

4.求一个数的平方根

package interview.squareroot;

public class SquareRoot {

    public static void main(String[] args) {
        double x = 0;
        double A = 3;
        double eta = 0.001;
        while (true) {
            double loss = 0.5 * (A - Math.pow(x, 2));
            System.out.println("loss:"+loss);
            if (loss < 0.001)
                break;
            x = x + eta * (A - x);
        }
        System.out.println("3的平方根是" + x);
    }
}