Skip to content

Latest commit

 

History

History
90 lines (77 loc) · 2.69 KB

543_二叉树的直径.md

File metadata and controls

90 lines (77 loc) · 2.69 KB
import java.util.*;

/**
 * @author : xfhy
 * Create time : 2020年11月12日08:17:09
 * Description : 543. 二叉树的直径
 * source : https://leetcode-cn.com/problems/diameter-of-binary-tree/
 */
public class Solution {

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

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

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }

        @Override
        public String toString() {
            return "TreeNode{" +
                    "val=" + val +
                    ", left=" + left +
                    ", right=" + right +
                    '}';
        }
    }

    private static int max = 1;

    /**
     * 思路: 经过一个节点的最大路径,可看作以某个节点为起点,找到该节点的左子树的最大深度+和右子树的最大深度+1
     * 我们只需要递归,找到经过每个节点的最大路径,然后记录最大值即可.
     */
    public static int diameterOfBinaryTree(TreeNode root) {
        depth(root);
        return max - 1;
    }

    private static int depth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        //左边节点的最大深度
        int l = depth(root.left);
        //右边节点的最大深度
        int r = depth(root.right);
        //经过当前根节点的最大路径 和 max进行比较,记录最大值
        max = Math.max(l + r + 1, max);
        //返回以该节点为根的子树的最大深度
        return Math.max(l, r) + 1;
    }

    public static TreeNode createBinaryTree(LinkedList<Integer> inputList) {
        if (inputList == null || inputList.isEmpty()) {
            return null;
        }
        TreeNode node = null;
        Integer data = inputList.removeFirst();
        if (data != null) {
            node = new TreeNode(data);
            node.left = createBinaryTree(inputList);
            node.right = createBinaryTree(inputList);
        }
        return node;
    }

    public static void main(String[] args) {
        /*LinkedList<Integer> integers = new LinkedList<>(Arrays.asList(5, 4, 11, 7, null, null, 2, null, null, null, 8, 13, null, null, 4,
                5, null, null, 1));*/
        /*LinkedList<Integer> integers = new LinkedList<>(Arrays.asList(3, 2, 9, null, null, 10, null,
                null, 8, null, 4));*/
        LinkedList<Integer> integers = new LinkedList<>(Arrays.asList(0, null, 1));
        TreeNode binaryTree = createBinaryTree(integers);

        int res = diameterOfBinaryTree(binaryTree);
        System.out.println(res);
    }

}