满二叉树
如果二叉树中除了叶子节点,每个节点的度都为2
则该二叉树为满二叉树
满二叉树不存在度为1的节点
完全二叉树
如果二叉树中除去最后一层节点(叶子节点)为满二叉树
切最后一层节点从左到右分布(中间不能有空)
则这个二叉树交左完全二叉树
JS创建二叉树
//反转二叉树
//若根节点不为空,将左右节点交换,直到根节点未空
function reverseBinaryTree(root)
{
if(root!=null)
{
var temp=root.left;
root.left=root.right;
root.right=temp;
reverseBinaryTree(root.left);
reverseBinaryTree(root.right);
}
return root;
}
//创建二叉树
function BinaryTree()
{
//一颗二叉树具有的性质=>节点Node,插入节点方法insertNode,取得根节点方法getRoot
var root=null;//根节点为空
this.getRoot=function()
{
return root;
}
function Node()
{
//二叉树的节点
this.key=key;
this.left=null;
this.right=null;
}
function insertNode(parentNode,childNode)
{
if(childNode.key<parentNode.key)
{
if(parentNode.left==null)
{
parentNode.left=childNode;
}
else
{
//直到找到没有儿子的左子树为止
insertNode(parentNode.left,childNode);
}
}
else
{
if(parentNode.right==null)
{
parentNode.right=childNode;
}
else
{
//直到找到没有儿子的右子树为止
insertNode(parentNode.right,childNode);
}
}
}
//插入方法
this.insert=function(key)
{
var node=new Node(key);
if(root==null)
{
root=node;
}
else
{
insertNode(root,node);
}
}
}
var node=[1,2,5,6,7,9,5,2,5,6,3];
var binaryTree=new BinaryTree();
node.forEach(item=>{
binaryTree.isert(item);
})
console.log(binaryTree.getRoot());
//前序遍历二叉树(写在BinaryTree里面)
this.preOrder=function(node)
{
if(node!=null)
{
console.log(node.key);
this.preOrder(node.left);
this.preOrder(node.right);
}
}
//中序遍历二叉树
this.inOrder(node)
{
if(node!=null)
{
this.inOrder(node.left);
console.log(node.key);
this.inOrder(node.right);
}
}
//后续遍历二叉树
this.postOrder(node)
{
if(node!=null)
{
this.inOrder(node.left);
this.inOrder(node.right);
console.log(node.key);
}
}
//广度优先遍历二叉树
this.levelOrder(node)
{
console.log(node.key)
if(node.left)
{
this.levelOrder(node.left);
}
if(node.right)
{
this.levelOrder(node.right);
}
}
//查找最小节点
this.findMinNode(node)
{
if(node!=null)
{
while(node&&node.left!=null)
{
node=node.left;
}
return node.key;
}
return null;
}
//查找指定节点
this.findItem(node,key)
{
if(node!=null)
{
if(key<node.key)
{
return this.findItem(node.left,key)
}
else if(key>node.key)
{
return this.findItem(node.right,key)
}
else
return true;
}
return null;
}
二叉搜索(查找)树-
所有左子树节点的值小于根节点的值,所有右子树节点的值大于根节点的值。
平衡二叉树
平衡二叉树的意思就是,左右节点的深度之差不超过一。
它的左子树和右子树都是平衡二叉树,且左子树和右子树的深度之差的绝对值不超过1。