二叉树三种遍历的非递归思路(JAVASCRIPT)

来源:互联网 发布:阿里云弹性ip有什么用 编辑:程序博客网 时间:2024/05/19 11:44

二叉树在图论中是这样定义的:二叉树是一个连通的无环图,并且每一个顶点的度不大于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 left subtree are traversed, and the right tree goes        if(stack.length!=0){            p = stack.pop();            p = p.right;        }    }    return res;};

前序遍历第二种方法:

var preorderTraversal = function(root) {  var result = [];  var stack = [];  var p = root;  while(stack.length!=0 || p != null) {      if(p != null) {          stack.push(p);          result.push(p.val); // Add before going to children          p = p.left;      } else {          var node = stack.pop();          p = node.right;      }  }  return result;};

中序遍历

第一种方法:

var inorderTraversal = function(root) {  var stack = [];  var res = [];  var p = root;  if(root == null) return [];  while( stack.length!=0 || p!=null){      while(p!=null){          stack.push(p);          p = p.left;      }      if(stack.length!=0){          p= stack.pop();          res.push(p.val);          p = p.right;      }  }  return res;};

第二种方法:

var inorderTraversal = function(root) {  var result = [];  var stack = [];  var p = root;  while(stack.length!=0 || p != null) {      if(p != null) {      stack.push(p);      p = p.left;  } else {      var node = stack.pop();      result.push(node.val); // Add after all left children      p = node.right;  }  }  return result;};

后序遍历

第一种方法:
var postorderTraversal = function(root) {  var Stack = [];    var result = [];    if(root==null)        return [];    Stack.push(root);    while(Stack.length!=0)    {      var node= Stack.pop();        result.push(node.val);        if(node.left)        Stack.push(node.left);        if(node.right)        Stack.push(node.right);    }    return result.reverse();};

第二种方法:

var postorderTraversal = function(root) {  var result = [];  var stack = [];  var p = root;  while(stack.length!=0 || p != null) {  if(p != null) {  stack.push(p);  result.unshift(p.val); // Reverse the process of preorder  p = p.right; // Reverse the process of preorder  } else {  var node = stack.pop();  p = node.left; // Reverse the process of preorder  }  }  return result;};
原创粉丝点击