算法练习Day15 (Leetcode/Python-二叉树)

110. Balanced Binary Tree

Given a binary tree, determine if it is height-balanced.

思路: 判断二叉树是否平衡,也就是二叉树的任何节点的左右子树高度差值不能超过1。这和求子树高度的题目类似。使用递归法时,但凡有个节点的左右子树高度差超过1,就一直return -1了,也就是不满足balanced了。

# 递归法
class Solution:
    def isBalanced(self, root: Optional[TreeNode]) -> bool:
        return self.get_hight(root) != -1
    def get_hight(self, node):
        if not node:
            return 0
        left = self.get_hight(node.left)
        right = self.get_hight(node.right)
        if left == -1 or right == -1 or abs(left - right) > 1:
            return -1
        return max(left, right) + 1

# 迭代法
class Solution:
    def isBalanced(self, root: Optional[TreeNode]) -> bool:
        if not root:
            return True

        height_map = {}
        stack = [root]
        while stack:
            node = stack.pop()
            if node:
                stack.append(node)
                stack.append(None)
                if node.left: stack.append(node.left)
                if node.right: stack.append(node.right)
            else:
                real_node = stack.pop()
                left, right = height_map.get(real_node.left, 0), height_map.get(real_node.right, 0)
                if abs(left - right) > 1:
                    return False
                height_map[real_node] = 1 + max(left, right)
        return True

257. Binary Tree Paths

Given the root of a binary tree, return all root-to-leaf paths in any order.

leaf is a node with no children.

思路:这里用迭代法,记录从root到当前节点的路径path于path_st。当当前节点为叶节点后,将到该叶节点的这条路径push入path中。并在处理完stack中所有节点后,输出path。stack后进先出来实现DFS。

class Solution(object):
    def binaryTreePaths(self, root):
        stack, path_st, result = [root], [str(root.val)], []
        while stack:
            cur = stack.pop()
            path = path_st.pop()

            if not (cur.left or cur.right):
                result.append(path)
            if cur.right:
                stack.append(cur.right)
                path_st.append(path + '->' + str(cur.right.val))
            if cur.left:
                stack.append(cur.left)
                path_st.append(path + '->' + str(cur.left.val))

        return result

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值