A collegiate textbook problem. Nothing special, but just take care of your memory use.class Solution {public: TreeNode *_buildTree(int pre[], int &...
分类:
其他好文 时间:
2014-07-23 12:00:46
阅读次数:
248
递归实现当然太简单,也用不着为了ac走这样的捷径吧。。非递归实现还挺有意思的。树的非递归遍历一定要借助栈,相当于把原来编译器做的事情显式的写出来。对于中序遍历,先要訪问最左下的节点,一定是进入循环后,不断的往左下走,走到不能走为止,这时候,能够从栈中弹出訪问的节点,相当于“左根右”过程的“根”,然后...
分类:
其他好文 时间:
2014-07-22 23:39:17
阅读次数:
296
关于二叉树的遍历有很多的方法, 下面介绍两个经典的遍历算法: BFS和DFS。一个是深度优先遍历, 一个是广度有优先遍历。 这两种遍历算法均属于盲目的遍历算法, 一般而言, 启发式的遍历搜索算法比较好一些。 。 关于各种遍历算法的对比, 将会在后面逐一提及。 这里不在赘述。
由于树是一个非线性的数据结构, 显然不能像linked list , 或者Array那样通过从头像最末尾移动去实现遍历每一...
分类:
编程语言 时间:
2014-07-20 23:14:21
阅读次数:
387
这里讲讲对binary Tree 进行level order Traversal.。 即BF traversal(广度优先遍历)。即首先, 访问根节点F, 打印出数据。 接着访问level 1的所有节点, 即D, J。 访问完level1之后, 访问level2, 即B, E, G , K 等等一次访问下去, 直至遍历完所有的节点。
BFS遍历的思路很简单, 但是当我们编程实现的时候,...
分类:
编程语言 时间:
2014-07-20 23:11:21
阅读次数:
344
如下图:
这里我们实现DFS中的三种遍历方法。
相关的如下:
相关算法的介绍不再赘述。
首先对于preorder traversal 的步骤为:
其他两种算法略。
具体递归调用分析, 注意学会画stack frame的图分析。 这里不再赘述。
代码如下:
/* Binary Tree Traversal - Preorder, Inorder, Postor...
分类:
编程语言 时间:
2014-07-20 23:05:10
阅读次数:
365
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...
分类:
其他好文 时间:
2014-07-20 22:41:23
阅读次数:
303
Validate Binary Search TreeRecover Binary Search TreeSymmetric TreeSame TreeMaximum Depth of Binary TreeConstruct Binary Tree from Preorder and Inorde...
分类:
其他好文 时间:
2014-07-19 20:17:42
阅读次数:
268
Given inorder and postorder traversal of a tree, construct the binary tree.Note:You may assume that duplicates do not exist in the tree.题解:如下图所示的一棵树: ...
分类:
其他好文 时间:
2014-07-19 19:00:44
阅读次数:
262
Given preorder and inorder traversal of a tree, construct the binary tree.Note:You may assume that duplicates do not exist in the tree.类似http://www.cn...
分类:
其他好文 时间:
2014-07-19 18:19:06
阅读次数:
243
Given a binary tree, return thebottom-up level ordertraversal of its nodes' values. (ie, from left to right, level by level from leaf to root).For exa...
分类:
其他好文 时间:
2014-07-18 20:06:13
阅读次数:
255