本文主要是介绍leetcode104 Maximum Depth Of Binary Java,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
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.
1、递归解法。两行
public int maxDepth(TreeNode root) {if(root == null) return 0;return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));}
2、非递归解法。队列
public int maxDepth(TreeNode root) {if(root == null) return 0;int result = 0;Queue<TreeNode> queue = new LinkedList<>();queue.offer(root);while(!queue.isEmpty()) {int size = queue.size();for(int i=0; i<size; i++) {TreeNode curr = queue.poll();if(curr.left !=null) queue.offer(curr.left);if(curr.right !=null) queue.offer(curr.right);}result ++;}return result ;}
这篇关于leetcode104 Maximum Depth Of Binary Java的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!