Skip to content

二叉树的中序遍历 #195

Open
Open

Description

@louzhedong

二叉树的中序遍历

对于任意一个节点,先遍历他的左子树,再遍历本身,再遍历右子树,最后得到一个升序的数组

实现

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 inorderSearch(root) {
  var array = [];

  _inorderSearch(root, array);
  return array;
}

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

Activity

  1. changed the title [-]二叉树的先序遍历[/-] [+]二叉树的中序遍历[/+] on Jan 14, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions