import java.util.LinkedList;
import java.util.Queue;
class TreeNode {
int val;
TreeNode left;
TreeNode right;
// 构造函数
TreeNode() {}
TreeNode(int val)
{ this.val = val; }
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
class Solution {
// 通过层序遍历得到树最大深度
// 层序遍历用到了队列,每经历一层将新一层的节点加到队列中,将旧一层的节点移出队列
public int maxDepth(TreeNode root){
int depth = 0;
Queue<TreeNode> queueNode = new LinkedList<>();
queueNode.add(root);
while (!queueNode.isEmpty()){
for (int i = 0; i < queueNode.size(); i++) {
if(queueNode.peek().left != null)queueNode.add(queueNode.peek().left);
if(queueNode.peek().right != null)queueNode.add(queueNode.peek().right);
queueNode.poll();
}
depth++;
}
return depth;
}
}
class test{
public static void main(String[] args) {
TreeNode node1 = new TreeNode(1);
TreeNode node2 = new TreeNode(2);
TreeNode node3 = new TreeNode(3);
TreeNode node4 = new TreeNode(4);
TreeNode node5 = new TreeNode(5);
TreeNode node6 = new TreeNode(6);
TreeNode node7 = new TreeNode(7);
node1.left = node2;node1.right = node3;
node2.left = node4;node2.right = node5;
node3.left = node6;node3.right = node7;
System.out.println(new Solution().maxDepth(node1));
}
}
树-求最大深度的层序遍历解法
最新推荐文章于 2021-12-22 15:15:01 发布