平衡二叉树

  • 输入一棵二叉树,判断该二叉树是否是平衡二叉树。 

方法一: 

public class Solution {
    public boolean IsBalanced_Solution(TreeNode root) {
        return process(root).isB;
    }
    public class ReturnData{
        boolean isB;
        int h;
        public ReturnData(boolean isB, int h){
            this.isB = isB;
            this.h = h;
        }
    }
    
    public ReturnData process(TreeNode root){
        if (root == null)
            return new ReturnData(true, 0);
        ReturnData leftData = process(root.left);
        if (leftData.isB == false)
            return new ReturnData(false,0);
        ReturnData rightData = process(root.right);
        if (rightData.isB == false)
            return new ReturnData(false,0);
        if (Math.abs(leftData.h - rightData.h) > 1)
            return new ReturnData(false, 0);
        return new ReturnData(true,Math.max(leftData.h ,rightData.h)+1);
    }
}

方法二:

public class IsBalancedTree {

	public static class Node {
		public int value;
		public Node left;
		public Node right;

		public Node(int data) {
			this.value = data;
		}
	}

	public static boolean isBalance(Node head) {
		boolean[] res = new boolean[1];
		res[0] = true;
		getHeight(head, 1, res);
		return res[0];
	}

	public static int getHeight(Node head, int level, boolean[] res) {
		if (head == null) {
			return level;
		}
		int lH = getHeight(head.left, level + 1, res);
		if (!res[0]) {
			return level;
		}
		int rH = getHeight(head.right, level + 1, res);
		if (!res[0]) {
			return level;
		}
		if (Math.abs(lH - rH) > 1) {
			res[0] = false;
		}
		return Math.max(lH, rH);
	}
}

 

你可能感兴趣的:(二叉树,平衡二叉树,刷题)