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. 下载imagenet2012数据集

    摸索了一下,imagenet2012下载,跟大家分享一下 用迅雷会员加速都可以下载,有的用百度云也可以离线下载 http://www.image-net.org/challenges/LSVRC/20 ...

  2. RabbitMQ简介

    AMQP简介 在了解RabbitMQ之前,首先要了解AMQP协议.AMQP,即Advanced Message Queuing Protocol,高级消息队列协议,是应用层协议的一个开放标准,为面向消 ...

  3. mysql命令总结

    统计全库数据量: use information_schema; SELECT TABLE_NAME, (DATA_LENGTH) as DataM , (INDEX_LENGTH) as Index ...

  4. python程序一直在后台运行的解决办法

    刚写了个python程序,要一直在后台运行,即使断开ssh进程也在,下面是解决办法: 假如Python程序为test.py 编写shell脚本start.sh #!/bin/bash python t ...

  5. java源码分析:Arrays.sort

    仔细分析java的Arrays.sort(version 1.71, 04/21/06)后发现,java对primitive(int,float等原型数据)数组采用快速排序,对Object对象数组采用 ...

  6. 收藏一些好用的fifo

    1.Nordic库中的 E:\nRF52_SDK_0.9.2_dbc28c9\components\libraries\fifo app_fifo.c /* Copyright (c) 2013 No ...

  7. PhpStorm 8.x/9.x 快捷键设置/个性化设置,如何多项目共存?如何更换主题?

    1."自定义"常用快捷键(设置成跟Eclipse差不多) 按照路径:File -> Settings -> Appearance & Behavior -> ...

  8. 微信公共服务平台开发(.Net 的实现)12-------网页授权(上 :更加深入理解OAuth2.0 )

    我们首先来认识一下OAuth协议吧,这个东西很早就听说过,总觉得离我很远(我的项目用不到这些),但是最近不得不学习一下了.我在网上找了一些解释,认为解释的最好的是这样说的(出处:http://hi.b ...

  9. Codeforces 699D Fix a Tree 并查集

    原题:http://codeforces.com/contest/699/problem/D 题目中所描述的从属关系,可以看作是一个一个块,可以用并查集来维护这个森林.这些从属关系中会有两种环,第一种 ...

  10. php之JavaScript

    JS对于大小写敏感 作用:增加跟html页面的交互性. 应用:验证表单.创建cookies(可插入html页面的编程代码)js插入页面后可由所有现代的浏览器执行.应用于<body>< ...