二叉树深度&二叉树是否平衡

思路:

1、递归取深度

2、递归判断每个节点是否平衡

代码:

package com.my.test.datastructure.tree;

/**
 * 求二叉树深度
 * &&
 * 判断是否是平衡二叉树
 */
public class BinaryTreeDepth
{

    static class Node {
        int value;
        Node left;
        Node right;
        Node(int value) {
            this.value = value;
        }
    }
    
    /**
     * 获取二叉树深度--递归
     * 
     */
    public static int getTreeDepth(Node root) {
        if (root == null) {
            return 0;
        }
        int left = getTreeDepth(root.left);
        int right = getTreeDepth(root.right);
        
        return left > right ? left + 1 : right + 1;
    }
    
    /**
     * 是否是平衡数--递归
     */
    public static boolean isBalanceTree(Node root) {
        // 为空时平衡的
        if (root == null) {
            return true;
        }
        
        // 判断该节点是否是平衡树
        int left = getTreeDepth(root.left);
        int right = getTreeDepth(root.right);
        if (Math.abs(left - right) > 1) {
            return false;
        }
        
        // 判断子节点
        return isBalanceTree(root.left) && isBalanceTree(root.right); 
    }
    
    public static void main(String[] args)
    {
        Node root = createBinaryTree();
        System.out.println(getTreeDepth(root));
        System.out.println(isBalanceTree(root));
    }
    
    private static Node createBinaryTree() {
        Node root = new Node(0);
        Node node1 = new Node(1);
        Node node2 = new Node(2);
        
        root.left = node1;
        root.right = node2;
        
        Node node3 = new Node(3);
        node1.left = node3;
        
        Node node4 = new Node(4);
        node3.left = node4;
        
        return root;
    }

}

参考:

https://blog.csdn.net/derrantcm/article/details/46771529

猜你喜欢

转载自blog.csdn.net/zangdaiyang1991/article/details/88657944