算法练习LeetCode初级算法之树
二叉树的前序遍历
我的解法:利用递归,自底向下逐步添加到list,返回最终的前序遍历list
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> list=new ArrayList<>();
if (root==null) {
return list;
}
list.add(root.val);
if (root.left!=null) {
list.addAll(preorderTraversal(root.left));
}
if (root.right!=null) {
list.addAll(preorderTraversal(root.right));
}
return list;
}
}
参考解法:利用递归,但只在外部建一个list,更好理解!
class Solution {
public List<Integer> list=new LinkedList<>();
public List<Integer> preorderTraversal(TreeNode root) {
if (root==null)
return list;
list.add(root.val);
preorderTraversal(root.left);
preorderTraversal(root.right);
return list;
}
}
中序遍历二叉树,同样有两种方法
第一种
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> list=new ArrayList<>();
if (root==null) {
return list;
}
if (root.left!=null) {
list.addAll(inorderTraversal(root.left));
}
list.add(root.val);
if (root.right!=null) {
list.addAll(inorderTraversal(root.right));
}
return list;
}
}
第二种
class Solution {
List<Integer> list=new ArrayList<>();
public List<Integer> inorderTraversal(TreeNode root) {
if (root==null) {
return list;
}
inorderTraversal(root.left);
list.add(root.val);
inorderTraversal(root.right);
return list;
}
}
后序遍历二叉树:也有两种方法,和前面的差不多,所以只写简洁的
class Solution {
List<Integer> list=new ArrayList<>();
public List<Integer> postorderTraversal(TreeNode root) {
if (root==null) {
return list;
}
postorderTraversal(root.left);
postorderTraversal(root.right);
list.add(root.val);
return list;
}
}
层次遍历二叉树
队列解法:
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> res=new ArrayList<>();
if (root==null) {
return res;
}
Queue<TreeNode> queue=new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()) {
int count=queue.size();
List<Integer> list=new LinkedList<>();
while (count>0) {
TreeNode node=queue.poll();
list.add(node.val);
if (node.left!=null) {
queue.add(node.left);
}
if (node.right!=null) {
queue.add(node.right);
}
count--;
}
res.add(list);
}
return res;
}
}
递归解法:参考大神的代码!!!
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> res=new ArrayList<>();
if (root==null) {
return res;
}
addList(res, 0, root);
return res;
}
private void addList(List<List<Integer>> res,int level,TreeNode head) {
if (head==null) {
return;
}
if (res.size()<=level) { //这里有个问题,如果不是等于的话
res.add(new ArrayList<>());
}
res.get(level).add(head.val);//这里的将会越界,因为level=res.size()取不到
addList(res, level+1, head.left);
addList(res, level+1, head.right);
}
}
二叉树的最大深度
递归
class Solution {
public int maxDepth(TreeNode root) {
if (root==null) {
return 0;
}
int leftH=maxDepth(root.left);
int rightH=maxDepth(root.right);
return Math.max(leftH, rightH)+1;
}
}
迭代
这个方法太难了,不优先考虑!!
class Solution {
public int maxDepth(TreeNode root) {
Queue<Pair<TreeNode,Integer>> queue=new LinkedList<>();
if (root!=null) {
queue.add(new Pair<TreeNode, Integer>(root, 1));
}
int depth=0;
while (!queue.isEmpty()) {
Pair<TreeNode,Integer> pair=queue.poll();
root=pair.getKey();
int pair_depth=pair.getValue();
if (root!=null) {
depth=Math.max(depth, pair_depth);
queue.add(new Pair<TreeNode, Integer>(root.left, pair_depth+1));
queue.add(new Pair<TreeNode, Integer>(root.right, pair_depth+1));
}
}
return depth;
}
}
对称二叉树
递归
class Solution {
public boolean isSymmetric(TreeNode root) {
return isMirror(root, root);
}
private boolean isMirror(TreeNode t1,TreeNode t2) {
if (t1==null&&t2==null) {
return true;
}
if (t1==null||t2==null) {
return false;
}
return (t1.val==t2.val)&&isMirror(t1.left, t2.right)
&&isMirror(t1.right,t2.left);
}
}
迭代
class Solution {
public boolean isSymmetric(TreeNode root) {
Queue<TreeNode> queue=new LinkedList<>();
if (root==null||(root.left==null&&root.right==null)) {
return true;
}
queue.add(root.left);
queue.add(root.right);
while (!queue.isEmpty()) {
TreeNode t1=queue.poll();
TreeNode t2=queue.poll();
if (t1==null&&t2==null) continue;
if(t1==null||t2==null) return false;
if(t1.val!=t2.val) return false;
queue.add(t1.left);
queue.add(t2.right);
queue.add(t1.right);
queue.add(t2.left);
}
return true;
}
}
路径总和:递归很简洁
class Solution {
public boolean hasPathSum(TreeNode root, int sum) {
if (root==null) {
return false;
}
if (root.left==null&&root.right==null) {
return sum-root.val==0;
}
return hasPathSum(root.right, sum-root.val)||
hasPathSum(root.left, sum-root.val);
}
}
验证二叉搜索树
利用中序遍历法:简单易懂
class Solution {
public boolean isValidBST(TreeNode root) {
if (root==null) {
return true;
}
List<Integer> list=new ArrayList<>();
inOrder(root, list);
for (int i = 0; i < list.size()-1; i++) {
if (list.get(i+1)<=list.get(i)) {
return false;
}
}
return true;
}
private void inOrder(TreeNode node,List<Integer> list) {
if (node==null) {
return;
}
inOrder(node.left, list);
list.add(node.val);
inOrder(node.right, list);
}
}
大神递归法:
class Solution {
double last=-Double.MAX_VALUE;
public boolean isValidBST(TreeNode root) {
if (root==null) {
return true;
}
if (isValidBST(root.left)) {
if (last<root.val) {
last=root.val;
return isValidBST(root.right);
}
}
return false;
}
}
堆桟法
public boolean isValidBST(TreeNode root) {
Stack<TreeNode> stack = new Stack();
TreeNode p = root;
Integer preVal = null ;
while( p != null || !stack.isEmpty() ){
if(p != null){
stack.push(p);
p = p.left;
}else{
p = stack.pop();
int val = p.val;
if(preVal == null){
preVal = val;
}else{
if(val <= preVal){
return false;
}
preVal = val;
}
p = p.right;
}
}
return true;
}
将有序数组转换为二叉搜索树
解法一
class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
return buildBST(nums, 0, nums.length-1);
}
private TreeNode buildBST(int[] nums,int l,int r) {
if (l>r) {
return null;
}
if (l==r) {
return new TreeNode(nums[l]);
}
int mid=(r+l)/2;
TreeNode root=new TreeNode(nums[mid]);
root.left=buildBST(nums, l, mid-1);
root.right=buildBST(nums, mid+1, r);
return root;
}
}
总结:递归是万能的,但递归真的很恶心!!!
算法练习LeetCode初级算法之树的更多相关文章
- 【LeetCode算法】LeetCode初级算法——字符串
在LeetCode初级算法的字符串专题中,共给出了九道题目,分别为:反转字符串,整数反转,字符串中的第一个唯一字符,有效的字母异位词,验证回文字符串,字符串转换整数,实现strStr(),报数,最 ...
- 算法练习LeetCode初级算法之链表
删除链表中的节点 /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode ne ...
- 算法练习LeetCode初级算法之字符串
反转字符串 我的解法比较low,利用集合的工具类Collections.reverse反转,用时过长 class Solution { public void reverseString(char[] ...
- 算法练习LeetCode初级算法之数组
删除数组中的重复项 官方解答: 旋转数组 存在重复元素 只出现一次的数 官方解答: 同一个字符进行两次异或运算就会回到原来的值 两个数组的交集 II import java.util.Arr ...
- 算法练习LeetCode初级算法之其他
位1的个数 解法一: class Solution { // you need to treat n as an unsigned value public int hammingWeight(int ...
- 算法练习LeetCode初级算法之数学
Fizz Buzz class Solution { public List<String> fizzBuzz(int n) { List<String> list=new L ...
- 算法练习LeetCode初级算法之设计问题
打乱数组 不断的让第一个与后面随机选择的数交换 class Solution { private int[] nums; private int[] initnums; public Solution ...
- 算法练习LeetCode初级算法之动态规划
爬楼梯:斐波那契数列 假设你正在爬楼梯.需要 n 阶你才能到达楼顶. 每次你可以爬 1 或 2 个台阶.你有多少种不同的方法可以爬到楼顶呢? 注意:给定 n 是一个正整数. 非递归解法 class S ...
- 算法练习LeetCode初级算法之排序和搜索
合并两个有序数组 class Solution { public void merge(int[] nums1, int m, int[] nums2, int n) { System.arrayco ...
随机推荐
- (32)forms组件(渲染自建规则:局部钩子函数和全局钩子函数)
要达成渲染自建规则 1.局部钩子函数(某个字段,自定意义规则,不如不能以sb开头,数据库已存在等) 2.全局钩子函数(校验两次密码是否一致) 3.使用css样式 register.html <! ...
- smartgit的安装
smartgit是非常好用的一个图形化git工具,有Ubuntu版本的,直接去官网下载即可,但使用smartgit要求先jre. 直接去官网上下载jre:https://www.java.com/zh ...
- JavaScript数据类型(第一天)
ECMAScript为JavaScript的标准,javascript为网景公司定义,但并不标准,所以欧洲的组织定义了ESMAScript,定义了网页脚本的标准. js组成 ECMAScript js ...
- kvm创建新虚拟机
安装图形化管理界面yum install virt-manager -y 安装好之后 新建虚拟机,我使用的方法是使用ISO镜像文件安装 选择镜像 设置内存 如此,一步一步走下去即可,不再截图 创建好之 ...
- vim 简单实用
http://www.runoob.com/linux/linux-vim.html 编辑模式 : (同时打开两个文件) vim test.c test1.c -O 同时编辑两个文件 - ...
- fork exec source的区别
参考:http://www.cnblogs.com/bkygg/p/5023072.html 1:fork 运行的时候开一个sub_shell 执行调用的脚本,sub_shell执行的时候,pare ...
- zabbix安装、部署、lnmp(一)
最近入手zabbix,准备好好的研究,好好的弄. 环境准备: mysql:5.6.29 PHP:5.6.12 Nginx:1.8.0 zabbix:3.2.6 操作系统:Centos6 用户:普通 ...
- centos7怎么查看、打开和关闭防火墙
使用centos7会发现,用centos6以前的方式查看.打开和关闭防火墙都无效了.这是因为centos7的防火墙改用firewalld,而不再使用iptables了 查看centos7的防火墙的状态 ...
- 十六、springcloud(二)Eureka集群
1.创建子工程spring-cloud-peer(jar) 2.创建application-peer1.properties,application-peer2.properties applicat ...
- No input file specified.
no input file specified 解决方法 2018年02月23日 14:25:07 tiramisuer8023 阅读数:36607 版权声明:本文为博主原创文章,未经博主允许不得 ...