代码随想录算法训练营第十七天 | 110. 平衡二叉树、257. 二叉树的所有路径、404. 左叶子之和

80 阅读1分钟

110. 平衡二叉树

代码随想录视频讲解

代码随想录文章讲解

递归法

  • 注意二叉树的高度求法:左右子树中较大的高度+1. 叶子节点要返回-1,这样+1才能是0
  • 左右子树的高度差最大为1,所以是<2
  • 二叉树节点的深度:指从根节点到该节点的最长简单路径边的条数。
  • 二叉树节点的高度:指从该节点到叶子节点的最长简单路径边的条数。
class Solution:
    def isBalanced(self, root: Optional[TreeNode]) -> bool:
        if not root:
            return True
        return abs(self.height_of_tree(root.left)-self.height_of_tree(root.right)) < 2 and self.isBalanced(root.left) and self.isBalanced(root.right)
​
    def height_of_tree(self, root):
        if not root:
            return -1
        return max(self.height_of_tree(root.left), self.height_of_tree(root.right)) + 1

迭代法(统一迭代法)

  • 使用stack和迭代模拟后序遍历
  • 使用None来分割需要处理的root节点
class Solution:
    def isBalanced(self, root: Optional[TreeNode]) -> bool:
        if not root:
            return True
​
        stack = deque([root])
        height_map = {}
        while stack:
            cur = stack.pop()
            if cur:
                # pop order: left - right - root
                # root
                stack.append(cur)
                stack.append(None)
                # right
                if cur.right:
                    stack.append(cur.right)
                # left
                if cur.left:
                    stack.append(cur.left)
            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. 二叉树的所有路径

代码随想录视频讲解

代码随想录文章讲解

递归法(使用后序遍历)

class Solution:
    def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
        if not root:
            return []
​
        # leaf node
        if not root.left and not root.right:
            return [str(root.val)]
​
        # left, right
        res = self.binaryTreePaths(root.left) + self.binaryTreePaths(root.right)
​
        # root
        return [str(root.val) + '->' + s for s in res]

递归法(使用前序遍历)

class Solution:
    def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
        if not root:
            return []
        res = []
        path = ""
        self.traversal(root, path, res)
        return res
​
    def traversal(self, cur, path, res):
        # root
        path += str(cur.val)
​
        # leaf node, append the path to res
        if not cur.left and not cur.right:
            return res.append(path)
​
        # left
        if cur.left:
            self.traversal(cur.left, path + "->", res)
        # right
        if cur.right:
            self.traversal(cur.right, path + "->", res)

迭代法(使用栈模拟前序遍历)

class Solution:
    def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
        if not root:
            return []
​
        stack = deque([root])
        path_stack = deque([str(root.val)])
        res = []
        while stack:
            cur = stack.pop()
            path = path_stack.pop()
​
            # leaf node
            if not cur.left and not cur.right:
                res.append(path)
​
            if cur.right:
                stack.append(cur.right)
                path_stack.append(path + "->" + str(cur.right.val))
​
            if cur.left:
                stack.append(cur.left)
                path_stack.append(path + "->" + str(cur.left.val))
​
        return res

404. 左叶子之和

代码随想录视频讲解

代码随想录文章讲解

递归法(后序遍历)

class Solution:
    def sumOfLeftLeaves(self, root: TreeNode) -> int:
        if not root: 
            return 0
        
        left_left_leaves_sum = self.sumOfLeftLeaves(root.left)  # 左
        right_left_leaves_sum = self.sumOfLeftLeaves(root.right) # 右
        
        cur_left_leaf_val = 0
        if root.left and not root.left.left and not root.left.right: 
            cur_left_leaf_val = root.left.val 
            
        return cur_left_leaf_val + left_left_leaves_sum + right_left_leaves_sum # 中

迭代法

class Solution:
    def sumOfLeftLeaves(self, root: Optional[TreeNode]) -> int:
        if not root:
            return 0
        
        left_leaf_sum = 0
        stack = deque([root])
        while stack:
            cur = stack.pop()
            if cur.left:
              # left leaf
                if not cur.left.left and not cur.left.right:
                    left_leaf_sum += cur.left.val
                else:
                    stack.append(cur.left)
            if cur.right:
                stack.append(cur.right)
                
        return left_leaf_sum