Recursion is a magical method, and the code looks simple.
Recursive methods can be used to traverse and find the maximum depth of a binary tree. The main idea is to traverse the left subtree and then traverse the right subtree. If there is a right child in the node on the left subtree, call the method of the right subtree. When traversing to the leaf node on the left subtree, return and start traversing the right subtree. If the node on the right tree has a left child, call the method of the left child tree to traverse the leaf node on the right child tree, and the program ends.
Static void scanNodes (TreeNode root) {if (root = null) {return;} System. out. println (root. val); // first traverse scanNodes (root. left); // System. out. println (root. val); traverse scanNodes (root. right); // System. out. println (root. val); Backward traversal}
This is also the idea of finding the maximum depth of a binary tree. You only need to add a return value.
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;}
The complete test code, which contains the Binary Tree node definition, is attached below.
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 traverse scanNodes (root. left); // System. out. println (root. val); traverse scanNodes (root. right); // System. out. println (root. val); Backward 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 running result is as follows:
1
2
3
4
The depth of the tree is: 3