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。