File tree Expand file tree Collapse file tree 1 file changed +74
-0
lines changed
Expand file tree Collapse file tree 1 file changed +74
-0
lines changed Original file line number Diff line number Diff line change 1+ #### ** 题目** :一棵二叉树,求最大通路长度(即最大左右子树高度之和)
2+
3+ #### ** 参考答案** :
4+
5+ 该题与leetcode第104题同题型,定义TreeNode结构如下:
6+
7+ ``` java
8+ class TreeNode {
9+
10+ int val;
11+ TreeNode left;
12+ TreeNode right;
13+
14+ public TreeNode (int val ) {
15+ this . val = val;
16+ }
17+ }
18+ ```
19+
20+ 解法一(递归求解)
21+ ``` java
22+ class Solution {
23+
24+ public int maxHeight (TreeNode root ) {
25+ if (root == null ) {
26+ return 0 ;
27+ }
28+ return maxChildHeight(root. left) + maxChildHeight(root. right);
29+ }
30+
31+ public int maxChildHeight (TreeNode root ) {
32+ if (root == null ) {
33+ return 0 ;
34+ }
35+ int leftHeight = maxChildHeight(root. left);
36+ int rightHeight = maxChildHeight(root. right);
37+ return Math . max(leftHeight, rightHeight) + 1 ;
38+ }
39+ }
40+ ```
41+
42+ 解法二(迭代求解)
43+ ``` java
44+ public class Solution {
45+
46+ public int maxHeight (TreeNode root ) {
47+ if (root == null ) {
48+ return 0 ;
49+ }
50+ return maxChildHeight(root. left) + maxChildHeight(root. right);
51+ }
52+
53+ public int maxChildHeight (TreeNode root ) {
54+ int height = 0 ;
55+ Queue<TreeNode > queue = new LinkedList<> ();
56+ queue. add(root);
57+
58+ while (! queue. isEmpty()) {
59+ int size = queue. size();
60+ for (int i = 0 ; i < size; i++ ) {
61+ TreeNode node = queue. poll();
62+ height++ ;
63+ if (node. left != null ) {
64+ queue. add(node. left);
65+ }
66+ if (node. right != null ) {
67+ queue. add(node. right);
68+ }
69+ }
70+ }
71+ return height;
72+ }
73+ }
74+ ```
You can’t perform that action at this time.
0 commit comments