Maximum Depth of Binary Tree
Posted 白常福
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Maximum Depth of Binary Tree相关的知识,希望对你有一定的参考价值。
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.
分析:用层次遍历,记录下访问深度即可。参考 http://www.cnblogs.com/baichangfu/p/7461433.html
JAVA CODE
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public int maxDepth(TreeNode root) { int deep = 0; Queue<TreeNode> queue = new ArrayDeque<>(); Queue<Integer> queue1 = new ArrayDeque<>(); if(root!=null){ queue.offer(root); queue1.offer(new Integer(deep++)); } while(!queue.isEmpty()){ root = queue.poll(); int hh = queue1.poll().intValue(); if(deep == hh){ deep++; } if(root.left!=null){ queue.offer(root.left); queue1.offer(new Integer(deep)); } if(root.right!=null){ queue.offer(root.right); queue1.offer(new Integer(deep)); } } return deep; } }
以上是关于Maximum Depth of Binary Tree的主要内容,如果未能解决你的问题,请参考以下文章
104. Maximum Depth of Binary Tree
[Lintcode]97. Maximum Depth of Binary Tree/[Leetcode]104. Maximum Depth of Binary Tree
104. Maximum Depth of Binary Tree