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;
}
}