二叉树在图论中是这样定义的:二叉树是一个连通的无环图,并且每一个顶点的度不大于3。有根二叉树还要满足根结点的度不大于2。有了根结点之后,每个顶点定义了唯一的父结点,和最多2个子结点。然而,没有足够的信息来区分左结点和右结点。如果不考虑连通性,允许图中有多个连通分量,这样的结构叫做森林。
这里,我使用javascript来写二叉树遍历的三种非递归方式,因为楼主学的是javascript,对于C,JAVA,C++这个都不是很熟,所以就只好使用javascript代替;
前序遍历
第一种方法:
var preorderTraversal = function(root) {
var stack = [];
var res = [];
var p = root;
if(root == null)return [];
while(stack.length!=0 || p!=null){
//Side by side to join the array, and deposited in the stack, the future need to use these root nodes into the right sub-tree
while(p!=null){
stack.push(p);
res.push(p.val);
p = p.left;
}
// When p is empty, it means that both the root and the l