Home  >  Article  >  Backend Development  >  How to find the length of the longest path in a binary tree

How to find the length of the longest path in a binary tree

坏嘻嘻
坏嘻嘻Original
2018-09-17 09:25:215365browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn