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]
]
这其实是层次遍历,但是每一层之后都要在队列中加入null。当从队列中读到null的时候,说明旧的一层结束了。
root之后的null在循环前加入。
读到最后一层之后的null的时候要特殊处理,要判断是否是空队列,是的话就不再加入null。
109. Convert Sorted List to Binary Search Tree
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
关键要有一个currentNode, 作为域被各个函数调用并不断更新。
length==2和3也要当作特殊例子处理,否则会超时。

左子树根据长度创建完以后除了给出左子树的根节点还可以直接给出根节点(左子树的父节点)。

创建左子树的时候要不停地更新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] 题型整理之二叉树的更多相关文章

  1. [leetcode] 题型整理之动态规划

    动态规划属于技巧性比较强的题目,如果看到过原题的话,对解题很有帮助 55. Jump Game Given an array of non-negative integers, you are ini ...

  2. [leetcode] 题型整理之排列组合

    一般用dfs来做 最简单的一种: 17. Letter Combinations of a Phone Number Given a digit string, return all possible ...

  3. [leetcode] 题型整理之数字加减乘除乘方开根号组合数计算取余

    需要注意overflow,特别是Integer.MIN_VALUE这个数字. 需要掌握二分法. 不用除法的除法,分而治之的乘方 2. Add Two Numbers You are given two ...

  4. [leetcode] 题型整理之cycle

    找到环的起点. 一快一慢相遇初,从头再走再相逢.

  5. [leetcode]题型整理之用bit统计个数

    137. Single Number II Given an array of integers, every element appears three times except for one. ...

  6. [leetcode] 题型整理之图论

    图论的常见题目有两类,一类是求两点间最短距离,另一类是拓扑排序,两种写起来都很烦. 求最短路径: 127. Word Ladder Given two words (beginWord and end ...

  7. [leetcode] 题型整理之查找

    1. 普通的二分法查找查找等于target的数字 2. 还可以查找小于target的数字中最小的数字和大于target的数字中最大的数字 由于新的查找结果总是比旧的查找结果更接近于target,因此只 ...

  8. [leetcode] 题型整理之排序

    75. Sort Colors Given an array with n objects colored red, white or blue, sort them so that objects ...

  9. [leetcode] 题型整理之字符串处理

    71. Simplify Path Given an absolute path for a file (Unix-style), simplify it. For example,path = &q ...

随机推荐

  1. 变量改变时PHP内核做了些什么?

    引言 内容来自于<Extending and Embedding PHP>- Chaper 3 - Memory Management,加上自己的理解,对php中变量的引用计数.写时复制, ...

  2. yaf设置命名空间

    修改yaf配置文件 文件是:yaf.ini extension=yaf.so yaf.use_namespace=1 index文件. 目录是application/controllers/Index ...

  3. 初次使用并安装express

    安装 Nodejs 去Nodejs官网根据自己的操作系统下载对应的安装包并安装.我们就有了NodeJS和npm环境.npm是Node的包管理工具,会在安装NodeJS时一并安装.可以用以下命令查看版本 ...

  4. 基本 sql语句

    1.打开数据库 int sqlite3_open( const char *filename,   // 数据库的文件路径 sqlite3 **ppDb          // 数据库实例 ); 2. ...

  5. 如何撤销 PhpStorm/Clion 等 JetBrains 产品的 “Mark as Plain Text” 操作 ?

    当把某个文件“Mark as Plain Text”时,该文件被当做普通文本,就不会有“代码自动完成提示”功能,如下图所示: 但是呢,右键菜单中貌似没有 相应的撤销 操作, 即使是把它删除,再新建一个 ...

  6. PhpStorm 9.03 集成 开源中国(oschina.net)的Git项目,提交SVN时注意事项

    第一步:配置 git.exe File -> Default Settings -> Version Control -> Git -> Path go Git executa ...

  7. CentOS6.3安装MongoDB2.2 及 安装PHP的MongoDB客户端

    下载源码:(放到 /usr/local/src 目录下) 到官网 http://www.mongodb.org/downloads 下载源码 https://fastdl.mongodb.org/li ...

  8. getComputedStyle的简单用法

    var number=window.getComputedStyle("元素").style样式名

  9. fdatool 设计IIR滤波器

    [B,A] = sos2tf(SOS);K = cumprod(G);k=K(end); [y_out] = filter(B, A, win_up_data, []) .*k;

  10. 一次dell R420 电源故障引发的“血案”

    说“血案”有写夸张了,其实是也就熬了一夜的通宵,做运维的伤不起啊,作为一名运维工程师,像这种服务器突发故障半夜起床的情况属于家常便饭,见怪不怪了,开始说正事: 前几天半夜12点左右,收到服务器宕机的消 ...