由二叉树概念引起的基本操作

1、二叉树的基本实现

  • 存储结构:顺序存储和类似于链表的链式存储
  • 表示形式:孩子表示法、孩子双亲表示法、孩子兄弟表示法等

2、二叉树的遍历

1> 概念:遍历就是指沿着某条搜索线路,依次对树中每个结点做一次且仅作一次的访问。访问结点所做的操作依赖于具体问题(比如打印结点内容,结点内容加一等)
2>三种遍历方式

  • NLR:前序遍历(Preoder Traversal) ,根 左子树 右子树
  • LNR:中序遍历(Inorder Traversal),左子树 根 右右子树
  • LRN:后序遍历(Postorder Traversal),左子树 右子树 根
    注意:以整体到局部角度考虑,一棵二叉树,首先分成根和左右子树,
    再局部到各个子树的根和左右子树,直到递归的出口条件(递归很顽固,
    不到底绝不归,所以遍历的时候每个子树一定要走完)

3、由概念引起的基本操作递归实现

//孩子表示法造一棵二叉树
class BTNode{
	BTNode left; //左节点
	BTNode right; //右节点
	int val;	//值
	
	public BTNode(int val) {
		this.val = val;
	}
}

//前序遍历(DFS),根、左、右 并将结点值域打印
public void preOrder(BTNode root) {
	if(root != root) {
		System.out.println(root.val);
		preOrder(root.left);
		preOrder(root.right);
	}
}

//中序遍历,左、根、右 
public void inOrder(BTNode root) {
	if(root != null) {
		inOrder(root.left);
		System.out.println(root.val);
		inOrder(root.right);
	}
}

//后序遍历,左、右、根
public void postOrder(BTNode root) {
	if(root != null) {
		postOrder(root.left);
		postOrder(root.right);
		System.out.println(root.val);
	}
}

//层序遍历(BFS)
public void laverOrder(BTNode root) {
	if(root == null) {
		return;
	}
	Queue<BTNode> q = new LinkedList<>();
		q.offer(root);
	while(!q.isEmpty()) {
		//取队头
		BTNode cur = q.poll();
		System.out.println(cur.val);
		//cur的左子树
		if(cur.left != null) {
			q.offer(cur.left);
		}
		if(cur.right != null) {
			q.offer(cur.right);
		}
	}
}


//求一棵二叉树叶子结点的个数
public int getLeafNode(BTNode root) {
	if(root == null) {
		return 0;
	}
	if(root.left == null && root.right == null) {
		return getLeafNode(root.left) + getLeafNode(root.right);
	}
}

//获取第K层结点的个数
public int countLevelNode(BTNode root,int k) {
	if(root == null || k < 1) {
		return 0;
	}
	if(k == 1) {
		return 1;
	}
	//求k-1层的结点树
	return countLevelNode(root.left,k-1) + countLevelNode(root.right,k-1);
}







发布了52 篇原创文章 · 获赞 6 · 访问量 1448

猜你喜欢

转载自blog.csdn.net/qq_40488936/article/details/104573676