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 to the farthest leaf node.
Code:
/*** Definition of TreeNode: * public class TreeNode {* public int val; * Public TreeNode left, right; * PU Blic TreeNode (int val) {* This.val = val; * This.left = This.right = null; *} *}*/ Public classSolution {/** * @paramroot:the root of binary tree. * @return: An integer. */ Private intDepth = 0; Public intmaxDepth (TreeNode root) {//Write your code here//Handle Corner case if(Root = =NULL) { return0; } //start from the rootHelper (Root, 1); returndepth; } Private voidHelper (TreeNode node,intcurtdepth) { //if reach the null if(node = =NULL) { return; } //Refresh Depth if(Curtdepth >depth) {Depth=curtdepth; } //go for left and rightHelper (Node.left, curtdepth + 1); Helper (node.right, curtdepth+ 1); }}
THR trick here's to set the depth variable and refresh it in the helper method, helper method is a Recu Rsive method, the return condition is when we reach the null node.
Lintcode:maximum Depth of Binary Tree