剑指offer-20200316

20200316

题目 :二叉树的深度

输入一棵二叉树的根节点,求该数的深度。从根节点到叶节点依次经过的节点(含根、叶节点)形成输的一条路径,最长的路径的长度为树的高度。

给定二叉树 [3,9,20,null,null,15,7],
	3
   / \
  9  20
    /  \
   15   7
返回它的最大深度 3 。

思路 :进行层次遍历即可知树的深度。

code

public int maxDepth(TreeNode root){
    if(root == null){
        return 0;
    }
    int count = 0;
    Queue<TreeNode> queue = new LinkedList<>();
    queue.offer(root);
    while(!queue.isEmpty()){
        count++;
        int size = queue.size();
        for(int i=0;i < size;i++){
            TreeNode cur = queue.poll();
            if(cur.left != null){
                queue.offer(cur.left);
            }
            if(cur.right != null){
                queue.offer(cur.right);
            }
        }
    }
    return count;
}
//双100%
class Solution{
    public int maxDepth(TreeNode root){
        if(root == null){
            return Math.max(maxDepth(root.left),maxDepth(root.right)) + 1;
        }
    }
}

题目 :平衡二叉树

输入一棵二叉树的根节点,判断该树是不是平衡二叉树。如果某二叉树中任意节点的左右子树的深度相差不超过1,那么他就是一棵平衡二叉树。

思路 :从左下角的最小二叉树开始比较,如果左边二叉树和右边二叉树不满足题意时,判断该二叉树不是二叉树。

class Solution{
    boolean flag = true;
    public boolean isBalanced(TreeNode root){
        if(root == null){
            return true;
        }
        helper(root);
        return flag;
    }
    
    public int helper(TreeNode root){
        if(root == null){
            return 0;
        }
        int left = helper(root.left);
        int right = helper(root.right);
        if(Math.abs(left - right) > 1){
            flag = false;
        }
        return Math.max(left,right) + 1;
    }
}

题目 :数组中数字出现的次数

一个整型数组 nums 里除两个数字之外,其他数字都出现了两次。请写程序找出这两个只出现一次的数字。要求时间复杂度是O(n),空间复杂度是O(1)。

思路 :对整个数组求异或,之后进行分组

class Solution {
    public int[] singleNumbers(int[] nums) {
        int temp = 0;
        for (int num : nums) {
            temp ^= num;
        }
        int mask = temp & (-temp);
        int[] res = new int[2];
        for (int num : nums) {
            if ((num & mask) == 0) {
                res[0] ^= num;
            } else {
                res[1] ^= num;
            } 
        }
        return res;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章