二叉树基本性质:
*根 root 节点度<=2
*儿子有序 左儿子 右儿子
*第level层的节点个数最多为:2^(level-1)
*深度为h的二叉树最多节点个数为2^h-1
满二叉树基本性质:
*节点个数=2^h-1
*节点层次=[log2 i]+1
*父节点 i=1根 i>1或 i<1 父节点=[i/2]
完全二叉树基本性质:
* 具有满二叉树大部分性质
* 仅有最后一层缺失部分节点
* 满二叉树属于完全二叉树
* 可以用数组表示
* 不需要记录父节点与子节点
二叉树的一个节点
Class TreeNode{
int key;
TreeNode left;
TreeNode right;
public void displayNode()
{
System.out.println(key);
}
}
二叉树的基本操作
1.查找一个节点
public TreeNode find(int key,TreeNode root)
{
TreeNode current=root;//从根节点开始查找
while(current!=null&¤t.val!=key)//如果当前遍历的节点为空或者不等于key则继续遍历
{
if(current.val>key)//如果点前遍历的节点值大于目标则目标值在当前节点的左子树
{
current=current.left;
}
else//如果点前遍历的节点值小于目标则目标值在当前节点的右子树
{
current=current.right;
}
}
return current;//返回结果 找不到则为为空 找得到则返回一个节点
}
2.插入一个结点
public void insert(TreeNode root,int val)
{
TreeNode node=new TreeNode(val);//新建一个待插入节点
if(root==null)
{
root=node;//如果根节点为空则在根节点处插入
}
else
{
TreeNode current=root;
TreeNode parent;
while(true)
{
parent=current;
if(current.val<=val)//如果当前节点小于等于插入值则插入位置在当前节点右边
{
current=current.right;
if(current==null)//当前节点为空则为新节点的插入位置
{
parent.right=node;//此时点前节点在父节点的右边所以新节点就放在父节点右边
return;
}
}
else //如果当前节点大于插入值则插入位置在当前节点左边
{
current=current.left;
if(current==null)//当前节点为空则为新节点的插入位置
{
parent.left=node;//此时点前节点在父节点的左边所以新节点就放在父节点左边
return;
}
}
}//while
}//else
}
二叉树的遍历
有三种遍历方式:前序(preorder),中序(inorder),后序(postorder)
1
2 3
4 5 6 7
1前序遍历
当前节点->左子节点->右子节点 结果 1-2-4-5-3-6-7
递归版
public void preorder(TreeNode root)
{
if(root==null)
{
return;
}
System.out.println(root.val);
preorder(root.left);
preorder(root.right);
}
非递归版
public void preorder(TreeNode root)
{
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
TreeNode p;
while(!stack.isEmpty())
{
p=stack.pop();
System.out.println(p.val);
if(p.right!=null)
{
stack.push(p.right);
}
if(p.left!=null)
{
stack.push(p.left);
}
}
}
2中序遍历
左子节点-> 当前节点->右子节点 结果 4-2-5-1-6-3-7
递归版
public void inorder(TreeNode root)
{
if(root==null)
{
return;
}
preorder(root.left);
System.out.println(root.val);
preorder(root.right);
}
非递归版
public void inorder(TreeNode root)
{
if(root==null)
{
return ;
}
Stack<TreeNode> stack=new Stack<>();
TreeNode r=root;
stack.push(root);
while(!stack.isEmpty())
{
while(r!=null)
{
r=r.left;
stack.push(r);
}
if(!stack.isEmpty())
{
r=stack.pop();
System.out.println(r.val);
r=r.right;
}
}//while
}
3后序遍历
左子节点-> 右子节点-> 当前节点 结果7-6-3-4-5-2-1
递归版
public void postorder(TreeNode root)
{
if(root==null)
{
return;
}
preorder(root.left);
preorder(root.right);
System.out.println(root.val);
}
参考资料:
https://www.bilibili.com/video/av19345520/
Java数据结构与算法第八章