Maximum Depth of Binary Tree,depthbinary
本文是在學習中的總結,歡迎轉載但請註明出處:http://blog.csdn.net/pistolove/article/details/41964475
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.
思路:
(1)題意為找到二叉樹最大深度:即為從樹根到葉子節點的最大路徑。
(2)該題思路和遍曆二叉樹和尋找二叉樹最短深度類似,可以參照二叉樹按層次遍曆實現http://blog.csdn.net/pistolove/article/details/41929059。
(3)為了求得二叉樹最大深度,本文也是考慮運用二叉樹按層次遍曆的思想,二叉樹遍曆層次的次數即為二叉樹的最大深度,這裡很容易理解。
(4)主要的解題思路還是二叉樹按層次遍曆。本文只不過順手把其拿過來使用罷了。希望對你有所協助。謝謝。
演算法代碼實現如下所示:
//最大深度public static int getDeep(TreeNode root){if(root==null) return 0;int level = 0;LinkedList<TreeNode> list = new LinkedList<TreeNode>();list.add(root);int first = 0;int last = 1;while(first<list.size()){last = list.size();while(first<last){if(list.get(first).left!=null){list.add(list.get(first).left);}if(list.get(first).right!=null){list.add(list.get(first).right);}first++;}level++;}return level;}