Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

二叉树的后序遍历 #197

Open
louzhedong opened this issue Jan 18, 2020 · 0 comments
Open

二叉树的后序遍历 #197

louzhedong opened this issue Jan 18, 2020 · 0 comments

Comments

@louzhedong
Copy link
Owner

二叉树的后序遍历

对于任意一个节点,先遍历他的左子树,再遍历右子树,再遍历本身。

实现

function Node(val) {
  this.left = null;
  this.right = null;
  this.value = val;
}

function generateBST(root,array) {
  var length = array.length;

  for (var i = 1; i < length; i ++) {
    insertNode(root, array[i]);
  }
}

function insertNode(node, value) {
  if (value < node.value) {
    if (node.left === null) {
      node.left = new Node(value);
    } else {
      node = node.left;
      insertNode(node, value);
    }
  } else {
    if (node.right === null) {
      node.right = new Node(value);
    } else {
      node = node.right;
      insertNode(node, value);
    }
  }
}

var array = [2, 3, 4, 12, 3, 54, 6, 7, 1];
var root = new Node(array[0]);

generateBST(root, array);


// 后序遍历
function postOrderSearch(root) {
  var array = [];

  _postOrderSearch(root, array);
  return array;
}

function _postOrderSearch(node, array) {
  if (!node) {
    return;
  }
  _postOrderSearch(node.left, array);
  _postOrderSearch(node.right, array);
  array.push(node.value);
}

console.log(postOrderSearch(root));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant