104. Maximum Depth of Binary Tree (Easy)

来源:互联网 发布:手机淘宝店名可以改吗 编辑:程序博客网 时间:2024/06/13 09:05

Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from
the root node down to the farthest leaf node.

题目即求二叉树的高度,层序遍历二叉树求解即可。

Solution:

Java:

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public int maxDepth(TreeNode root) {        if(root == null) {            return 0;        }        if(root.left == null && root.right == null) {            return 1;        }        int maxDepth = 0;        Queue<TreeNode> queue = new LinkedList<>();        queue.add(root);        int currentLevelCount = 1;        int nextLevelCount = 0;        while(!queue.isEmpty()) {            TreeNode node = queue.poll();            currentLevelCount--;            if(node.left != null) {                queue.add(node.left);                nextLevelCount++;            }            if(node.right != null) {                queue.add(node.right);                nextLevelCount++;            }            if(currentLevelCount == 0) {                currentLevelCount = nextLevelCount;                nextLevelCount = 0;                maxDepth++;            }        }        return maxDepth;    }}

非递归的层序遍历,通过队列来实现,使用currentLevelCount和nextLevelCount两个变量记录当前层的结点个数和下一层的结点个数。

0 0
原创粉丝点击