【重点】【二叉树】【DFS】剑指offer——面试题39-2:平衡二叉树

力扣
答案:https://leetcode.cn/problems/ping-heng-er-cha-shu-lcof/solutions/832191/ping-heng-er-cha-shu-by-leetcode-solutio-6r1g/

Python

只遍历1次,自底而上的递归,本质是后序遍历

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def isBalanced(self, root: Optional[TreeNode]) -> bool:
        res = self.judge(root)
        return res >= 0
    
    def judge(self, root) -> int:
        if root == None:
            return 0
        left_depth = self.judge(root.left)
        right_depth = self.judge(root.right)
        if left_depth == -1 or right_depth == -1 or abs(left_depth - right_depth) > 1:
            return -1
        else:
            return 1 + max(left_depth, right_depth)

Java

法1:遍历两次,思路一般

在这里插入图片描述

class Solution {
    public boolean isBalanced(TreeNode root) {
        if (root == null) {
            return true;
        }
        if (Math.abs(depth(root.left) - depth(root.right)) <= 1) {
            return isBalanced(root.left) && isBalanced(root.right);
        } else {
            return false;
        }
    }

    public int depth(TreeNode node) {
        if (node == null) {
            return 0;
        }
        return 1 + Math.max(depth(node.left), depth(node.right));
    }
}

法2:只遍历1次

在这里插入图片描述

class Solution {
    public boolean isBalanced(TreeNode root) {
        return depth(root) >= 0;
    }

    public int depth(TreeNode node) {
        if (node == null) {
            return 0;
        }
        int left = depth(node.left);
        int right = depth(node.right);
        if (left == -1 || right == -1 || Math.abs(left - right) > 1) {
            return -1;
        }
        return 1 + Math.max(left, right);
    }
}

20180906整理
##Solution1:
书上的思路,利用后序遍历,每个结点只遍历一次~

class Solution {
public:
    bool IsBalanced_Solution(TreeNode* pRoot) {
        int depth = 0;
        return IsBalanced(pRoot, depth);
    }
    bool IsBalanced(TreeNode *pRoot, int &depth) {
        if (pRoot == NULL) {
            depth = 0;
            return true;
        }
        int left, right;
        if (IsBalanced(pRoot->left, left) && 
            IsBalanced(pRoot->right, right)) {
            int diff = left - right;
            if (abs(diff) <= 1) {
                depth = 1 + max(left, right);
                return true;
            }
        }
        return false;
    }
};
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值