104. Maximum Depth of Binary Tree(1.private 2.void)
阿新 • • 發佈:2019-01-06
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.
/** * 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) { divide and conquer if (root==null){ return 0;//如果到葉子節點或者null值,return 0,高度不再增加 } int depth=1; int left = maxDepth(root.left); int right = maxDepth(root.right); return depth=Math.max(left,right)+1; */ //traverse private int depth; public int maxDepth(TreeNode root) { depth=0; helper(root, 1); return depth; } private void helper(TreeNode root, int curdepth){ if(root==null){ return;//void 方法的終止 } if(curdepth>depth){ depth=curdepth; } helper(root.left,curdepth+1); //在void型別中,不能有int left= helper(root.left,curdepth)+1; helper(root.right,curdepth+1); } }
知識點:
- void是java中的關鍵字,它代表的意思是什麼也不返回,我們在開發過程中經常會用到,如一個方法不需要返回值時可以使用void關鍵字,在main方法中也是void關鍵字。
Void類是用final修飾的,說明不可以擴充套件,另外構造方法是私有的,不可以例項化;Void類是一個不可例項化的佔位符類,用來儲存一個引用代表了Java關鍵字void的Class物件。
終止void:如果想在方法中的任何地方終止執行,可以使用return後面不加任何返回值
public void getName() { String name = "username"; if(name != null) return; System.out.println(name); } --------------------- 作者:隨風yy 來源:CSDN 原文:https://blog.csdn.net/yaomingyang/article/details/80180813 版權宣告:本文為博主原創文章,轉載請附上博文連結!
- private:訪問許可權僅限於類的內部,是一種封裝的體現,例如,大多數成員變數都是修飾符為private的,它們不希望被其他任何外部的類訪問。
public:可以被所有其他類所訪問
private:只能被自己訪問和修改
protected:自身、子類及同一個包中類可以訪問
default:同一包中的類可以訪問,宣告時沒有加修飾符,認為是friendly。