二叉树层序遍历:
class TreeNode {
TreeNode left;
TreeNode right;
int value;
}
void levelTraversal(TreeNode root) {
Queue<TreeNode> q = new LinkedList<>();
q.add(root);
while (!q.isEmpty()) {
TreeNode nowNode = q.poll();
if (nowNode != null) {
System.out.println(nowNode.value + " ");
//添加数据节点
if (nowNode.left != null) {
//如果左子节点不为null,则将子节点加入队列
q.add(nowNode.left);
}
if (nowNode.right != null) {
//如果右子节点不为null,则将子节点加入队列
q.add(nowNode.right);
}
}
}
}
求二叉树的最大深度:
int treeDepth(TreeNode root) {
Queue<TreeNode> q = new LinkedList<>();
q.add(root);
int depth = 0, count = 0, currentLevelCount = 1; //nextcount为该层应有的节点个数
while (!q.isEmpty()) {
TreeNode nowNode = q.poll();
count++;
if (nowNode != null) {
System.out.println(nowNode.value + " ");
//添加数据节点
if (nowNode.left != null) {
//如果左子节点不为null,则将子节点加入队列
q.add(nowNode.left);
}
if (nowNode.right != null) {
//如果右子节点不为null,则将子节点加入队列
q.add(nowNode.right);
}
if (count == currentLevelCount) { //此时该层已经遍历完,队列中的元素应为下一层结点个数
depth++;
count = 0;
currentLevelCount = q.size();
}
}
}
return depth;
}
//递归版本
public int TreeDepth(TreeNode root) {
if (root == null) return 0;
int nLeft = TreeDepth(root.left);
int nRight = TreeDepth(root.right);
return (nLeft > nRight) ? (nLeft + 1) : (nRight + 1);
}