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. ReactNative 从环境和第一个demo说起,填坑教程

    一.React-Native MacOS必备环境配置: 1.安装homebrew(这东西可以理解为命令行的app商店) /usr/bin/ruby -e "$(curl -fsSL http ...

  2. Photon服务器进阶&一个新游戏的出产(三)

    下面或许该介绍介绍我用Photon写的一个4人联机麻将了~ 上图

  3. CodeForces 165C Another Problem on Strings(组合)

    A string is binary, if it consists only of characters "0" and "1". String v is a ...

  4. SqlHelper c#

    using System; using System.Data; using System.Xml; using System.Data.SqlClient; using System.Collect ...

  5. 电商总结(五)移动M站建设

    最近在一直在搞M站,也就是移动web站点.由于是第一次,也遇到了很多问题,所以把最近了解到的东西总结总结.聊一聊什么是移动M站,它有啥作用和优势. 也有人会问,M站和APP有什么不同? 1. APP ...

  6. [Unity] Shader(着色器)输入输出和语义

    在Unity5.x后, 已经支持了基于物理的光照模型,也就是常说的次时代引擎所必须具备的功能. 如果在Properties使用2D,CG里要用sampler2D,代表使用的是2维纹理 如果在Prope ...

  7. VBA笔记(一)

    开启VBA编程环境--VBE 方法一:按<Alt+F11>组合建 方法二:查看代码 宏设置 当然启用宏的设置方式不同,宏的启动方式也不一样. 首先打开"office 按钮&quo ...

  8. PHP流式上传和表单上传(美图秀秀)

    最近需要开发一个头像上传的功能,找了很多都需要授权的,后来找到了美图秀秀,功能非常好用. <?php /** * Note:for octet-stream upload * 这个是流式上传PH ...

  9. PHP错误处理函数set_error_handler()的用法

    定义和用法 set_error_handler() 函数设置用户自定义的错误处理函数. 该函数用于创建运行时期间的用户自己的错误处理方法. 该函数会返回旧的错误处理程序,若失败,则返回 null. 语 ...

  10. PHP程序员进阶学习书籍参考指南

    PHP程序员进阶学习书籍参考指南 @heiyeluren lastmodify: 2016/2/18     [初阶](基础知识及入门)   01. <PHP与MySQL程序设计(第4版)> ...