problem:
Given a binary tree to find its maximum depth.
The depth of the binary tree is the root node to the nodes on the longest path farthest leaf node.
Description: leaf node is a node has no child nodes.
Example:
given binary tree [3,9,20, null, null, 15,7 ],
3
/ \
920
/ \
157
returns to its maximum depth 3.
Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/maximum-depth-of-binary-tree
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.
analysis:
To find the maximum depth of a binary tree, we must traverse the entire binary tree.
Extended:
Binary tree traversal
1. breadth-first traversal.
2. The depth-first traversal (recursive or means may be employed to traverse the stack)
Preorder traversal, in order traversal, postorder traversal.
Code:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int maxDepth(TreeNode root) {
int i=0;
return find(root,i);
}
public int find(TreeNode myNode,int i){
int ll=0;
int rr=0;
if(myNode==null){
return i;
}
i++;
ll=find(myNode.left,i);
rr=find(myNode.right,i);
return ll>rr ? ll:rr;
}
}
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
Advanced:
1. Stack traverse
2. The minimum depth of a binary tree
3. balanced binary tree