代码随想录算法训练营第16天 | 二叉树03

110.平衡二叉树
https://leetcode.cn/problems/balanced-binary-tree/submissions/540479822/
110.平衡二叉树代码随想录
https://programmercarl.com/0110.平衡二叉树.html
257. 二叉树的所有路径
https://leetcode.cn/problems/binary-tree-paths/submissions/540487197/
257. 二叉树的所有路径代码随想录
https://programmercarl.com/0257.二叉树的所有路径.html#算法公开课
404.左叶子之和 (优先掌握递归)https://leetcode.cn/problems/sum-of-left-leaves/submissions/
404.左叶子之和 (优先掌握递归)代码随行录
https://programmercarl.com/0404.左叶子之和.html
222.完全二叉树的节点个数(优先掌握递归)
https://leetcode.cn/problems/count-complete-tree-nodes/submissions/540520637/
完全二叉树节点个数 代码随想录
https://programmercarl.com/0222.完全二叉树的节点个数.html

110. 平衡二叉树

题目

给定一个二叉树,判断它是否是 平衡二叉树

题解重点:

  • 递归法:如果发现某一层不平衡 直接将-1传回去 这样传递,迭代到最终结果;
  • 迭代法:先利用迭代法栈求高度;再判断是否平衡(可以直接用字典存储)

题解代码

递归法

class Solution:
    def isBalanced(self, root: Optional[TreeNode]) -> bool:
        return self.getdeepth(root)!=-1

    def getdeepth(self,root):
        if not root:
            return 0
        right = self.getdeepth(root.right)
        left = self.getdeepth(root.left)
        if right==-1:
            return -1
        if left==-1:
            return -1
        if abs(right-left)>1:
            return -1
        else:
            return 1+max(self.getdeepth(root.right),self.getdeepth(root.left))

迭代法

class Solution:
    def isBalanced(self, root: Optional[TreeNode]) -> bool:
        if not root:
            return True
        st = [root]
        while st:
            node = st.pop()
            if node:
                st.append(node)
                st.append(None)
                if node.right:
                    st.append(node.right)
                if node.left:
                    st.append(node.left)
            else:
                curr =  st.pop()
                right = self.getdeepth(curr.right)
                left = self.getdeepth(curr.left)
                if abs(right-left)>1:
                    return False
        return True

    def getdeepth(self,root):
        if not root:
            return 0
        st = [root]
        dep = 0
        res = 0
        while st:
            node = st.pop()
            if node:
                st.append(node)
                st.append(None)
                dep = dep+1
                if node.right:
                    st.append(node.right)
                if node.left:
                    st.append(node.left)
            else:
                curr = st.pop()
                dep = dep-1
            res = max(res,dep)
        return res

257. 二叉树的所有路径

题目

给你一个二叉树的根节点 root ,按 任意顺序 ,返回所有从根节点到叶子节点的路径。

叶子节点 是指没有子节点的节点。

题解

  • 递归法:传递 trans 函数即可 trans 函数首先增加节点,然后判断左右子树
  • 迭代法:path回溯;添加一个path_st 和 node_st作用一样

题解代码

递归法

class Solution:
    def trans(self,curr,path,res):
        path.append(curr.val)
        if not curr.right and not curr.left:
            spath = '->'.join(map(str,path))
            res.append(spath)
            return
        if curr.left:
            self.trans(curr.left,path,res)
            path.pop()
        if curr.right:
            self.trans(curr.right,path,res)
            path.pop()

    def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
        res = []
        path = []
        if not root:
            return res
        self.trans(root,path,res)
        return res
class Solution:
    def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
        if not root:
            return []
        st = [root]
        path = [str(root.val)]
        res = []
        while st:
            node = st.pop()
            path_i = path.pop()
            if node:
                if node.right:
                    st.append(node.right)
                    path.append(path_i+'->'+str(node.right.val))
                if node.left:
                    st.append(node.left)
                    path.append(path_i+'->'+str(node.left.val))
                st.append(node)
                path.append(path_i)
                st.append(None)
            else:
                curr = st.pop()
                if not curr.right and not curr.left:
                    res.append(path_i)
        return res

左叶子之和

题目

给定二叉树的根节点 root ,返回所有左叶子之和。

题解

  • 递归法:停止逻辑:左叶子节点:直接返回左叶子节点;root的左子树的叶子节点+root的右子树的左叶子节点
  • 迭代法:遍历到左叶子节点求和即可

题解代码

递归法

class Solution:
    def sumOfLeftLeaves(self, root: Optional[TreeNode]) -> int:
        if not root:
            return 0
        if not root.left and not root.right:
            return 0
        left = self.sumOfLeftLeaves(root.left)
        if root.left and not root.left.left and not root.left.right:
            left = root.left.val
        right = self.sumOfLeftLeaves(root.right)
        return left+right

迭代法

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

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

题目

给你一棵 完全二叉树 的根节点 root ,求出该树的节点个数。

完全二叉树 的定义如下:在完全二叉树中,除了最底层节点可能没填满外,其余每层节点数都达到最大值,并且最下面一层的节点都集中在该层最左边的若干位置。若最底层为第 h 层,则该层包含 1~ 2h 个节点。

题解重点

  • 完全二叉树个数:2**height-1
  • 2<<0和2**\1等价

题解代码

递归法

class Solution:
    def countNodes(self, root: Optional[TreeNode]) -> int:
        if not root:
            return 0
        deep = 0
        left = root.left
        right = root.right
        while left and right:
            left = left.left
            right = right.right
            deep = deep+1
        if not left and not right:
            return (2<<deep)-1
        return 1+self.countNodes(root.left)+self.countNodes(root.right)
posted @ 2024-06-19 11:41  哆啦**  阅读(0)  评论(0编辑  收藏  举报