二叉树的深度

tech2024-04-22  221

题目

输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。

分析

代码

class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } } public class Test { public static void main(String[] args) { TreeNode root = new TreeNode(1); TreeNode node1 = new TreeNode(2); TreeNode node2 = new TreeNode(3); TreeNode node3 = new TreeNode(4); TreeNode node4 = new TreeNode(5); TreeNode node5 = new TreeNode(6); TreeNode node6 = new TreeNode(7); root.left = node1; root.right = node2; node1.left = node3; node1.right = node4; node2.right = node5; node4.left = node6; System.out.println(TreeDepth(root)); } public static int TreeDepth(TreeNode root) { if (root == null){ return 0; } int leftN = TreeDepth(root.left); int rightN = TreeDepth(root.right); System.out.println(leftN + " : " + rightN); return (leftN > rightN) ? (leftN+1) : (rightN+1); } }
最新回复(0)