算法练习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 ...
随机推荐
- spring--多人开发,模块化配置
需要在配置文件中配置: <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="h ...
- robot framework浏览器与驱动的匹配
一.谷歌浏览器和火狐浏览器与驱动不匹配产生的问题 1.若在运行过程中出现[Unable to find a matching set of capabilities ][ WebDriverExcep ...
- cordova打开文件系统插件的使用: cordova-plugin-file-opener2
1. 添加插件:cordova plugin add cordova-plugin-file-opener2 2. 调用方法: var target="/sdcard/Download/io ...
- MySQL Error--Error Code
mysql error code(备忘) 1005:创建表失败 1006:创建数据库失败 1007:数据库已存在,创建数据库失败 1008:数据库不存在,删除数据库失败 1009:不能删除数据库文件导 ...
- Redis缓存系统(一)Java-Jedis操作Redis,基本操作以及 实现对象保存
版权声明:本文为博主原创文章.未经博主同意不得转载. https://blog.csdn.net/jiangtao_st/article/details/37699473 源码下载: http://d ...
- Go语言开发Windows应用
Go语言开发Windows应用 当第一次看到Go程序在windows平台生成可执行的exe文件,就宣告了windows应用也一定是Go语言的战场.Go不是脚本语言,但却有着脚本语言的轻便简单的特性.相 ...
- Excel函数之rank应用
该函数的功能就是对现有数据指标进行排名 示例:对产品进行销售总额的排名 首先要知道排名需要用到rank函数 number参数就是你要进行排名的数据 ref参数就是该指标需要在哪个区域内进行比较定位排名 ...
- phpcms调用语句
title 标题:url 链接地址:thumb缩略图 :先调用moreinfo="1" content 内容: {php list($copyfrom) = explode('| ...
- VS2010 修改模板文件,增加默认注释
在开发过程中往往需要在每一个页面(类)增加注释等等内容,VS2010中可以修改模板,在原有模板中增加一个类,会引用System等等命名空 间,以及一些程序集.下面我们来看看如何增加自己需要一些说明,比 ...
- kafka命令大全
kafka命令大全 http://orchome.com/454