[leetcode] 题型整理之二叉树
94. Binary Tree Inorder Traversal
Given a binary tree, return the inorder traversal of its nodes' values.
For example:
Given binary tree [1,null,2,3]
,
1
\
2
/
3
return [1,3,2]
.
Note: Recursive solution is trivial, could you do it iteratively?
非递归前序遍历:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<Integer>();
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode hand = root;
while (hand != null) {
stack.push(hand);
hand = hand.left;
}
while (!stack.isEmpty()) {
TreeNode node = stack.pop();
result.add(node.val);
hand = node.right;
while (hand != null) {
stack.push(hand);
hand = hand.left;
}
}
return result;
}
}
103. Binary Tree Zigzag Level Order Traversal
Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).
For example:
Given binary tree [3,9,20,null,null,15,7]
,
3
/ \
9 20
/ \
15 7
return its zigzag level order traversal as:
[
[3],
[20,9],
[15,7]
]
左子树根据长度创建完以后除了给出左子树的根节点还可以直接给出根节点(左子树的父节点)。
创建左子树的时候要不停地更新currentNode。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
ListNode currentNode;
public TreeNode sortedListToBST(ListNode head) {
int length = 0;
ListNode hand = head;
while (hand != null) {
length++;
hand = hand.next;
}
currentNode = head;
return helper(length);
}
private TreeNode helper(int length) {
if (length == 0) {
return null;
}
if (length == 1) {
TreeNode result = new TreeNode(currentNode.val);
currentNode = currentNode.next;
return result;
}
if (length == 2) {
TreeNode l = new TreeNode(currentNode.val);
currentNode = currentNode.next;
TreeNode result = new TreeNode(currentNode.val);
currentNode = currentNode.next;
result.left = l;
return result;
}
if (length == 3) {
TreeNode l = new TreeNode(currentNode.val);
currentNode = currentNode.next;
TreeNode result = new TreeNode(currentNode.val);
currentNode = currentNode.next;
result.left = l;
TreeNode r = new TreeNode(currentNode.val);
currentNode = currentNode.next;
result.right = r;
return result;
}
TreeNode left = helper(length / 2);
TreeNode root = new TreeNode (currentNode.val);
currentNode = currentNode.next;
root.left = left;
root.right = helper(length - length / 2 - 1);
return root;
} }
148. Sort List
Sort a linked list in O(n log n) time using constant space complexity.
用mergesort做,跟上一题超级像。
144. Binary Tree Preorder Traversal
Given a binary tree, return the preorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3}
,
1
\
2
/
3
return [1,2,3]
.
Note: Recursive solution is trivial, could you do it iteratively?
非递归前序遍历
用栈,先根节点入栈之后一个个pop出来,父节点打印,右节点入栈,左节点作为先一个hand,直到hand是null为止。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null) {
return null;
}
if (p == root || q == root) {
return root;
}
TreeNode left = lowestCommonAncestor(root.left, p, q);
TreeNode right = lowestCommonAncestor(root.right, p, q);
if (left == null) {
return right;
} else if (right == null) {
return left;
} else {
return root;
}
}
}
255. Verify Preorder Sequence in Binary Search Tree
Given an array of numbers, verify whether it is the correct preorder traversal sequence of a binary search tree.
You may assume each number in the sequence is unique.
Follow up:
Could you do it using only constant space complexity?
解释参见grandyang的博客
[LeetCode] Verify Preorder Sequence in Binary Search Tree 验证二叉搜索树的先序序列
java代码如下:
public class Solution {
public boolean verifyPreorder(int[] preorder) {
Stack<Integer> stack = new Stack<Integer>();
int length = preorder.length;
if (length == 0) {
return true;
}
int low = Integer.MIN_VALUE;
int count = 0;
for (int i = 0; i < length; i++) {
int num = preorder[i];
if (num < low) {
return false;
}
while (count > 0 && preorder[count - 1] < num) {
count--;
low = preorder[count];
}
preorder[count] = num;
count++;
}
return true;
}
}
[leetcode] 题型整理之二叉树的更多相关文章
- [leetcode] 题型整理之动态规划
动态规划属于技巧性比较强的题目,如果看到过原题的话,对解题很有帮助 55. Jump Game Given an array of non-negative integers, you are ini ...
- [leetcode] 题型整理之排列组合
一般用dfs来做 最简单的一种: 17. Letter Combinations of a Phone Number Given a digit string, return all possible ...
- [leetcode] 题型整理之数字加减乘除乘方开根号组合数计算取余
需要注意overflow,特别是Integer.MIN_VALUE这个数字. 需要掌握二分法. 不用除法的除法,分而治之的乘方 2. Add Two Numbers You are given two ...
- [leetcode] 题型整理之cycle
找到环的起点. 一快一慢相遇初,从头再走再相逢.
- [leetcode]题型整理之用bit统计个数
137. Single Number II Given an array of integers, every element appears three times except for one. ...
- [leetcode] 题型整理之图论
图论的常见题目有两类,一类是求两点间最短距离,另一类是拓扑排序,两种写起来都很烦. 求最短路径: 127. Word Ladder Given two words (beginWord and end ...
- [leetcode] 题型整理之查找
1. 普通的二分法查找查找等于target的数字 2. 还可以查找小于target的数字中最小的数字和大于target的数字中最大的数字 由于新的查找结果总是比旧的查找结果更接近于target,因此只 ...
- [leetcode] 题型整理之排序
75. Sort Colors Given an array with n objects colored red, white or blue, sort them so that objects ...
- [leetcode] 题型整理之字符串处理
71. Simplify Path Given an absolute path for a file (Unix-style), simplify it. For example,path = &q ...
随机推荐
- Java并发编程之阻塞队列
1.什么是阻塞队列? 队列是一种数据结构,它有两个基本操作:在队列尾部加入一个元素,从队列头部移除一个元素.阻塞队里与普通的队列的区别在于,普通队列不会对当前线程产生阻塞,在面对类似消费者-生产者模型 ...
- web前端基础知识-(一)html基本操作
1. HTML概述 HTML是英文Hyper Text Mark-up Language(超文本标记语言)的缩写,他是一种制作万维网页面标准语言(标记).相当于定义统一的一套规则,大家都来遵守他,这样 ...
- mysql5.7导入csv文件
环境: Windows10企业版X64 mysql5.7免安装版(从5.6版本开始,官方不再提供64位的msi版本) 运行mysqld.exe启动mysql进程. 用root登录mysql: mysq ...
- mate标签
<meta charset='utf-8'> <!-- 优先使用 IE 最新版本和 Chrome --> <meta http-equiv="X-UA-C ...
- [NHibernate]事务
目录 写在前面 文档与系列文章 事务 增删改查 总结 写在前面 上篇文章介绍了nhibernate的增删改查方法及增加修改操作,这篇文章将介绍nhibernate的事务操作. SQL Server中的 ...
- Angular2.0快速开始
参考资料: Angular2.0快速开始 AngularJS2 教程
- php5 数据类型
一.PHP主要有一下几种数据类型 String(字符串), Integer(整型), Float(浮点型), Boolean(布尔型), Array(数组), Object(对象), NULL(空值) ...
- [Python] 学习笔记之MySQL数据库操作
1 Python标准数据库接口DB-API介绍 Python标准数据库接口为 Python DB-API,它为开发人员提供了数据库应用编程接口.Python DB-API支持很多种的数据库,你可以选择 ...
- average slice
A non-empty zero-indexed array A consisting of N integers is given. A pair of integers (P, Q), such ...
- jQuery如何退出each循环的?
试问:jQuery是如何退出each循环的? 在回调函数里return false即可,大多数jQuery的方法都是如此的. 返回 'false' , 将停止循环 (就像在普通的循环中使用 'bre ...