剑指offer之面试题55:二叉树的深度

面试题55:二叉树的深度

题目一:二叉树的深度
输入一颗二叉树的根节点,求该数的深度。从根节点到叶节点依次经过的节点(含根、叶节点)形成树的一条路径,最长路径的长度为树的深度。

思路:遍历二叉树,遍历的同时保存该节点的深度。(solve2的方法写的更简单,这种比较好)

代码实现:

package Question55;

public class T01 {

    private static int maxDepth = 0;

    public static void main(String[] args) {
        TreeNode node1 = new TreeNode(1);
        TreeNode node2 = new TreeNode(2);
        TreeNode node3 = new TreeNode(3);
        TreeNode node4 = new TreeNode(4);
        TreeNode node5 = new TreeNode(5);

        node2.leftChild = node1;
        node2.rightChild = node3;
        node3.leftChild = node4;
        node3.rightChild = node5;

        System.out.println(solve(node2));
    }

    public static int solve(TreeNode root) {
        help(root, 1);
        return maxDepth;
    }

    public static void help(TreeNode root, int depth) {
        if(root != null) {
            if(root.leftChild != null) help(root.leftChild, depth+1);
            if(root.leftChild == null && root.rightChild == null) {
                if(depth > maxDepth) maxDepth = depth;
            }
            if(root.rightChild != null) help(root.rightChild, depth+1);
        }
    }

	public static int solve2(TreeNode root) {
        if(root == null) return 0;
        int lDepth = solve2(root.leftChild);
        int rDepth = solve2(root.rightChild);
        return Math.max(lDepth, rDepth) + 1;
    }
}

class TreeNode {

    int val;
    TreeNode leftChild;
    TreeNode rightChild;

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

题目二:平衡二叉树
输入一颗二叉树的根节点,判断该树是不是平衡二叉树。如果某二叉树中任意节点的左、右子树的深度相差不超过1,那么它就是一颗平衡二叉树。

思路:在上一题的基础上,判断出来某一节点的左、右子树的深度之后,就可以判断该节点是不是平衡节点了,如果不是,我们返回-1,否则返回该节点的深度即可。

代码实现:

package Question55;

public class T02 {
    public static void main(String[] args) {
        TreeNode node1 = new TreeNode(1);
        TreeNode node2 = new TreeNode(2);
        TreeNode node3 = new TreeNode(3);
        TreeNode node4 = new TreeNode(4);
        TreeNode node5 = new TreeNode(5);

        node2.leftChild = node1;
        node2.rightChild = node3;
        node3.leftChild = node4;
        node3.rightChild = node5;

        System.out.println(solve(node2));
    }

    public static boolean solve(TreeNode root) {
        if(help(root) > 0) return true;
        else return false;
    }

    public static int help(TreeNode root) {
        if(root == null) return 0;
        int lDepth = help(root.leftChild);
        int rDepth = help(root.rightChild);
        if(lDepth == -1 || rDepth == -1 || Math.abs(lDepth - rDepth) >= 2) return -1;
        return Math.max(lDepth, rDepth) + 1;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值