本文共 1730 字,大约阅读时间需要 5 分钟。
/** * Definition for a binary tree node. * public 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) { if(root == null) { return 0; } //如果为空 直接返回0 int a = maxDepth(root.left); int b = maxDepth(root.right); return Math.max(a, b) + 1;//加上根节点的层数 }}
/** * Definition for a binary tree node. * public 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) { if(root == null) { return 0; } Queuequeue = new LinkedList<>(); queue.offer(root); int ans = 0; while(!queue.isEmpty()) { //记录每一行的节点个数 一行全部从队列拿完ans就加一 int size = queue.size(); while(size > 0) { TreeNode cur = queue.poll(); //拿出一个size-- size--; if(cur.left != null) { queue.offer(cur.left); } if(cur.right != null) { queue.offer(cur.right); } } //一行拿完 ans++; } return ans; }}
转载地址:http://qlhzi.baihongyu.com/