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

坏嘻嘻
Release: 2018-09-17 09:25:21
Original
5364 people have browsed it

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;
    }
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template