代码随想录 - Day24 - 完全二叉树,平衡二叉树

代码随想录 - Day24 - 完全二叉树,平衡二叉树

222. 完全二叉树的节点个数

  • 普通二叉树
    递归
# 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 countNodes(self, root: Optional[TreeNode]) -> int:
        return self.getNodeSum(root)

    def getNodeSum(self, cur):
        if not cur:
            return 0
        leftNum = self.getNodeSum(cur.left)
        rightNum = self.getNodeSum(cur.right)
        treeNum = leftNum + rightNum + 1
        return treeNum

迭代:层序遍历

class Solution:
    def countNodes(self, root: Optional[TreeNode]) -> int:
        if not root:
            return 0
        queue = collections.deque([root])
        sum = 0
        while queue:
            for i in range(len(queue)):
                node = queue.popleft()
                if node.left:
                    queue.append(node.left)
                if node.right:
                    queue.append(node.right)
                sum += 1
        return sum
  • 完全二叉树
class Solution:
    def countNodes(self, root: Optional[TreeNode]) -> int:
        if not root:
            return 0
        left = root.left        # 左树
        right = root.right      # 右树
        leftDepth = 0
        rightDepth = 0
        while left:             # 求左数深度
            left = left.left
            leftDepth += 1
        while right:            # 求右树深度
            right = right.right
            rightDepth += 1
        if leftDepth == rightDepth:         # 若左右深度相等则为满二叉树,直接用数学求解
            return (2 << leftDepth) - 1     # 2 << 1 相当于2^2,所以leftDepth初始为0
        return self.countNodes(root.left) + self.countNodes(root.right) + 1
# 另一种写法
class Solution:
    def countNodes(self, root: Optional[TreeNode]) -> int:
        if not root:
            return 0
        count = 0
        left = root.left        # 左树
        right = root.right      # 右树
        
        while left and right:
            count += 1
            left = left.left
            right = right.right
        if not left and not right:         # 若左右同时到底则为满二叉树,直接用数学求解
            return (2 << count) - 1
        return self.countNodes(root.left) + self.countNodes(root.right) + 1

2 << x2^(x+1)
2 ** x2^x
所以后两种写法的count初始值不同

# 另第二种写法
class Solution:
    def countNodes(self, root: Optional[TreeNode]) -> int:
        if not root:
            return 0
        count = 1
        left = root.left        # 左树
        right = root.right      # 右树
        
        while left and right:
            count += 1
            left = left.left
            right = right.right
        if not left and not right:         # 若左右同时到底则为满二叉树,直接用数学求解
            return (2 ** count) - 1
        return self.countNodes(root.left) + self.countNodes(root.right) + 1

110. 平衡二叉树

递归:比较高度,后序遍历

# 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:
        if self.getHeight(root) != -1:
            return True
        return False
        
    def getHeight(self, node):
        if not node:
            return 0
        leftHeight = self.getHeight(node.left)
        if leftHeight == -1:
            return -1
        rightHeight = self.getHeight(node.right)
        if rightHeight == -1:
            return -1
        result = 0
        if abs(leftHeight - rightHeight) > 1:
            result = -1
        else:
            result = 1 + max(leftHeight, rightHeight)
        return result

迭代:用栈模拟后序遍历找每一个节点的高度

class Solution:
    def getDepth(self, cur):
        st = []
        if cur is not None:
            st.append(cur)
        depth = 0
        result = 0
        while st:
            node = st[-1]
            if node is not None:
                st.pop()
                st.append(node)                           # 中
                st.append(None)
                depth += 1
                if node.right:
                    st.append(node.right)                 # 右
                if node.left:
                    st.append(node.left)                   # 左

            else:               
                node = st.pop()
                st.pop()
                depth -= 1
            result = max(result, depth)
        return result

    def isBalanced(self, root):
        st = []
        if root is None:
            return True
        st.append(root)
        while st:
            node = st.pop()                                 # 中
            if abs(self.getDepth(node.left) - self.getDepth(node.right)) > 1:
                return False
            if node.right:
                st.append(node.right)                       # 右(空节点不入栈)
            if node.left:
                st.append(node.left)                         # 左(空节点不入栈)
        return True

重点掌握递归法,迭代理解即可

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值