1. 程式人生 > >二叉樹三種遍歷的非遞迴思路(JAVASCRIPT)

二叉樹三種遍歷的非遞迴思路(JAVASCRIPT)

二叉樹在圖論中是這樣定義的:二叉樹是一個連通的無環圖,並且每一個頂點的度不大於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;

};