提交 4a78cbc6 编写于 作者: L liu13

20190120

上级 cad5a428
package code;
import java.util.ArrayDeque;
import java.util.Queue;
/*
* 104. Maximum Depth of Binary Tree
* 题意:二叉树最大深度
* 难度:Easy
* 分类:Tree, Depth-first Search
* 思路:深度优先搜索,递归实现
* 思路:深度优先搜索,递归实现。非递归BFS,相当于层序遍历。
* Tips:
*/
public class lc104 {
......@@ -19,4 +23,22 @@ public class lc104 {
return 0;
return Math.max(maxDepth(root.left),maxDepth(root.right)) + 1;
}
public int maxDepth2(TreeNode root) {
if(root==null) return 0;
Queue<TreeNode> q = new ArrayDeque<>();
q.add(root);
int depth = 0;
while(!q.isEmpty()){
int size = q.size();
while(size > 0){
TreeNode tn = q.remove();
if(tn.left!=null) q.add(tn.left);
if(tn.right!=null) q.add(tn.right);
size--;
}
depth++;
}
return depth;
}
}
package code;
import java.util.ArrayList;
import java.util.List;
/*
* 448. Find All Numbers Disappeared in an Array
* 题意:数组长度为n,数组中数字取值为1~n,有些数字可能出现多次,有些可能不出现,找出未出现的数字
* 难度:Easy
* 分类:Array
* 思路:把对应的数字放到对应的位置,最后遍历一遍,如果位置和数字不对应,则为缺失的值。
* Tips:
*/
public class lc448 {
public static void main(String[] args) {
System.out.println(findDisappearedNumbers(new int[]{4,3,2,7,8,2,3,1}));
}
public static List<Integer> findDisappearedNumbers(int[] nums) {
for (int i = 0; i < nums.length ; i++) {
if(nums[i]-1!=i && nums[nums[i]-1]!=nums[i]) {
int temp = nums[i];
nums[i] = nums[temp-1];
nums[temp-1] = temp;
i--;
}
}
List<Integer> res = new ArrayList<>();
for (int i = 0; i < nums.length ; i++) {
if(nums[i]!=i+1)
res.add(i+1);
}
return res;
}
}
package code;
/*
* 461. Hamming Distance
* 题意:转换为2进制,有几个位置上的值不同,就叫做Hamming distance
* 难度:Easy
* 分类:Bit Maniputation
* 思路:异或运算可以直接得出异或后二进制的结果,再统计1的个数即可
* Tips:
*/
public class lc461 {
public int hammingDistance(int x, int y) {
int num = x^y;
int res = 0;
while(num>0){
res += num%2;
num /= 2;
}
return res;
}
}
package code;
/*
* 538. Convert BST to Greater Tree
* 题意:二叉搜索树,让节点上的值+上所有比它大的值
* 难度:Easy
* 分类:Tree
* 思路:因为是二叉搜索树,右,中,左,这样遍历就可以最大的值递减遍历出结果了。
* 记住,不好递归返回值的,直接设置一个全局变量即可,简单方便。全局变量,全局变量,全局变量!!!
* Tips:
*/
public class lc538 {
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
int sum = 0;
public TreeNode convertBST(TreeNode root) {
helper(root);
return root;
}
public void helper(TreeNode root){
if(root==null) return;
helper(root.right);
root.val = root.val + sum;
sum = root.val;
helper(root.left);
}
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册