Recursion is a very magical method, and the code looks neat.
For the two-fork tree traversal and the maximum depth can be recursive method, the main idea is to traverse the left subtree, and then traverse the right subtree. If the node above the Zoozi tree has a right child, call the method of the right subtree, and when traversing to the leaf node of the left subtree, return and begin traversing the right subtree. If the node above the right subtree has a left child, then call the Zuozi method, traversing to the right subtree of the leaf node, when the program ends.
static void Scannodes (TreeNode root) {
if (root==null) {return
;
}
System.out.println (Root.val); First-order traversal
scannodes (root.left);
System.out.println (Root.val); Middle sequence Traversal
scannodes (root.right);
System.out.println (Root.val); Subsequent traversal
}
To find the maximum depth of the binary tree is also this idea, just add a return value can
static int getdepth (TreeNode root) {
if (root==null) {return
0;
}
int left=getdepth (root.left);
int right=getdepth (root.right);
Return left>right?left+1:right+1;
}
Attached below, the complete test code, which has two fork tree node definition, we can understand
Class TreeNode
{
TreeNode left;
TreeNode right;
int Val;
TreeNode (int val) {
this.val=val
}
Returns the depth of the binary tree
static int getdepth (TreeNode root) {
if (root==null) {return
0;
}
int left=getdepth (root.left);
int right=getdepth (root.right);
Return left>right?left+1:right+1;
}
static void Scannodes (TreeNode root) {
if (root==null) {return
;
}
System.out.println (Root.val); First-order traversal
scannodes (root.left);
System.out.println (Root.val); Middle sequence Traversal
scannodes (root.right);
System.out.println (Root.val); Subsequent traversal
} public
static void Main (string[] args)
{
TreeNode root=new TreeNode (1);
TreeNode left1=new TreeNode (2);
TreeNode left2=new TreeNode (3);
TreeNode right1=new TreeNode (4);
Create a tree
root.left=left1;
left1.right=left2;
root.right=right1;
Scannodes (root);
System.out.println ("The depth of the tree is:" +getdepth (Root));
}
The results of the operation are as follows:
1
2
3
4
The depth of the tree is: 3