1. 程式人生 > >110. 平衡二叉樹

110. 平衡二叉樹

jude pre hash color put treenode shm bsp root

110. 平衡二叉樹

https://leetcode-cn.com/problems/balanced-binary-tree/description/

package com.test;

/**
 * @author stono
 * @date 2018/9/1
 */
public class Lesson110 {
    public static void main(String[] args) {
        TreeNode t1 = new TreeNode(1);
        TreeNode t2 = new TreeNode(2);
        TreeNode t3 = new
TreeNode(3); t1.left = t2; t1.right = t3; TreeNode.printNode(t1); boolean balanced = isBalanced(t1); System.out.println(balanced); } public static boolean isBalanced(TreeNode root) { if (root == null) { return true; }
return judegeLeftRight(root.left,root.right); } private static boolean judegeLeftRight(TreeNode left, TreeNode right) { // 判斷根是否是平衡的 int res = Math.abs(treeHigh(left) - treeHigh(right)); if (res > 1) { return false; } // 判斷左右兩個樹是否是平衡的 return
isBalanced(left) && isBalanced(right); } /** * 計算樹的高度 * @param left * @return */ private static int treeHigh(TreeNode left) { if (left == null) { return 0; } return 1+Math.max(treeHigh(left.left),treeHigh(left.right)); } }

速度不是特別快,把樹的高度緩存了,還是不快:

package com.test;

import java.util.HashMap;
import java.util.Map;

/**
 * @author stono
 * @date 2018/9/1
 */
public class Lesson110_v2 {
    public static void main(String[] args) {
        TreeNode t1 = new TreeNode(1);
        TreeNode t2 = new TreeNode(2);
        TreeNode t3 = new TreeNode(3);
        t1.left = t2;
        t1.right = t3;
        TreeNode.printNode(t1);
        boolean balanced = isBalanced(t1);
        System.out.println(balanced);
    }
    public static boolean isBalanced(TreeNode root) {
        if (root == null) {
            return true;
        }
        return judegeLeftRight(root.left,root.right);
    }

    private static boolean judegeLeftRight(TreeNode left, TreeNode right) {
        Map<TreeNode, Integer> treeNodeHighMap = new HashMap<>(8);
        // 判斷根是否是平衡的
        int res = Math.abs(treeHigh(left,treeNodeHighMap) - treeHigh(right, treeNodeHighMap));
        if (res > 1) {
            return false;
        }
        // 判斷左右兩個樹是否是平衡的
        return isBalanced(left) && isBalanced(right);
    }

    /**
     * 計算樹的高度,計算過程中將TreeNode高度緩存
     * @param left
     * @return
     */
    private static int treeHigh(TreeNode left, Map<TreeNode, Integer> treeNodeHighMap) {
        // 先來取一下
        Integer integer = treeNodeHighMap.get(left);
        if (integer != null) {
            return integer;
        }
        if (left == null) {
            treeNodeHighMap.put(left, 0);
            return 0;
        }
        treeNodeHighMap.put(left, 1+Math.max(treeHigh(left.left, treeNodeHighMap),treeHigh(left.right, treeNodeHighMap)));
        return treeNodeHighMap.get(left);
    }
}

110. 平衡二叉樹