Home > Article > Backend Development > How to find the length of the longest path in a binary tree
The content of this article is about how to find the length of the longest path of a binary tree. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Input a binary tree and find the depth of the tree. The nodes (including root and leaf nodes) passing through in sequence from the root node to the leaf nodes form a path of the tree. The length of the longest path is the depth of the tree.
Problem-solving ideas: recursive algorithm
/** public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } } */import java.lang.Math;public class Solution { public int TreeDepth(TreeNode pRoot) { if(pRoot == null){ return 0; } int left = TreeDepth(pRoot.left); int right = TreeDepth(pRoot.right); return Math.max(left, right) + 1; } }
The above is the detailed content of How to find the length of the longest path in a binary tree. For more information, please follow other related articles on the PHP Chinese website!