Title: Enter a binary tree to find the depth of the tree. The length of the longest path is the depth of the tree, which is a path of the tree from the root node to the node of the leaf node (including root and leaf node).
Idea: the so-called depth refers to the length of the longest path from the root node to the leaf node, that is, the number of nodes on the path. To analyze the problem, enter root node root and ask its depth to find the depth of the root left and right subtree first, take its larger value, then add 1 is the depth of the current tree, that is obviously this is a two-fork tree after the subsequent traversal of the recursive process, design a recursive function, enter a node root, Returns the depth of the tree where the root knot is located.
Recursive relationships are:
Leftdepth=this.process (Root.left);
Rightdepth=this.process (Root.right);
Returnmath.max (leftdepth, rightdepth) +1;
Boundary conditions:
If (Root==null) return 0;
That is, for an empty tree node, it is clear that its depth is known, 0, the most boundary condition or initial condition.
This is a basic recursive function construction process, very simple, only a return value.
//depth, first find the depth of the left and right subtree, and then ask the depth of the current tree. The recursive process of subsequent traversal can be reformed.
Publicclass Solution {
public int treedepth (TreeNode root) {
//Special input
if (Root==null) return 0;
//Call recursive function to solve the problem
return this.process (root);
}
//Design a recursive function to find the depth of a binary tree
private int process (TreeNode root) {
the boundary condition of///recursive function
if (Root==null) return 0;
//① to find the depth of the left subtree
int leftdepth=this.process (root.left);
//② The depth of the right subtree
int rightdepth=this.process (root.right);
//③ processing the current node to find the depth of the current tree
Intdepth=math.max (leftdepth,rightdepth) +1;
//Return results
return depth;
} }