题目:一棵二叉树,求最大通路长度(即最大左右子树高度之和)

参考答案

该题与leetcode第104题同题型,定义TreeNode结构如下:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class TreeNode {

    int val;
    TreeNode left;
    TreeNode right;

    public TreeNode(int val) {
        this.val = val;
    }
}

解法一(递归求解)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {

    public int maxHeight(TreeNode root) {
        if (root == null) {
            return 0;
        }
        return maxChildHeight(root.left) + maxChildHeight(root.right);
    }

    public int maxChildHeight(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int leftHeight = maxChildHeight(root.left);
        int rightHeight = maxChildHeight(root.right);
        return Math.max(leftHeight, rightHeight) + 1;
    }
}

解法二(迭代求解)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public class Solution {

    public int maxHeight(TreeNode root) {
        if (root == null) {
            return 0;
        }
        return maxChildHeight(root.left) + maxChildHeight(root.right);
    }

    public int maxChildHeight(TreeNode root) {
        int height = 0;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);

        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                height++;
                if (node.left != null) {
                    queue.add(node.left);
                }
                if (node.right != null) {
                    queue.add(node.right);
                }
            }
        }
        return height;
    }
}