二叉の木の前の順序はJavaScriptを通って再帰的でないと再帰的に実現する方法です.

1061 ワード

//     : , , 
const TreeNode = {
  val: 1,
  left: {
    val: 2,
    left: {
      val: 4,
    },
    right: {
      val: 5
    }
  },
  right: {
    val: 3,
    left: {
      val: 6,
    },
    right: {
      val: 7
    }
  }
};

//            
var preOrderRecur = function(root){

  var list = [];
  var preOrder = function(root){
    if(root === undefined){
      return root;
    }
    list.push(root.val)
    preOrder(root.left);
    preOrder(root.right);
  }
  preOrder(root);
  return list;
};

//             
var preOrder = function(TreeNode){
  var list = [];
  let stack = [TreeNode];
  while(stack.length !== 0){
    const cur = stack.pop();
    const right = cur.right;
    const left = cur.left;
    list.push(cur.val);

    if(right){
      stack.push(right);
    }
    if(left){
      stack.push(left);
    }
  }
  return list;
  
  
}


var list = preOrderRecur(TreeNode);
console.log('      ', list);

var listUnRecur = preOrder(TreeNode);
console.log('       ', listUnRecur);

// [1, 2, 4, 5, 3, 6, 7]