代码随想录

代码随想录

树的最大深度

class solution:
    def maxdepth(self, root: treenode) -> int:
        return self.getdepth(root)
        
    def getdepth(self, node):
        if not node:
            return 0
        leftdepth = self.getdepth(node.left) #左
        rightdepth = self.getdepth(node.right) #右
        depth = 1 + max(leftdepth, rightdepth) #中
        return depth

树的最小深度

class Solution:
    def minDepth(self, root: TreeNode) -> int:
        if not root:
            return 0
        que = deque()
        que.append(root)
        res = 1

        while que:
            for _ in range(len(que)):
                node = que.popleft()
                # 当左右孩子都为空的时候,说明是最低点的一层了,退出
                if not node.left and not node.right:
                    return res
                if node.left is not None:
                    que.append(node.left)
                if node.right is not None:
                    que.append(node.right)
            res += 1
        return res

完全二叉树

class Solution:
    def countNodes(self, root: TreeNode) -> int:
        if not root:
            return 0
        left = root.left
        right = root.right
        leftHeight = 0 #这里初始为0是有目的的,为了下面求指数方便
        rightHeight = 0
        while left: #求左子树深度
            left = left.left
            leftHeight += 1
        while right: #求右子树深度
            right = right.right
            rightHeight += 1
        if leftHeight == rightHeight:
            return (2 << leftHeight) - 1 #注意(2<<1) 相当于2^2,所以leftHeight初始为0
        return self.countNodes(root.left) + self.countNodes(root.right) + 1

完全二叉树的节点个数

import collections
class Solution:
    def countNodes(self, root: TreeNode) -> int:
        queue = collections.deque()
        if root:
            queue.append(root)
        result = 0
        while queue:
            size = len(queue)
            for i in range(size):
                node = queue.popleft()
                result += 1 #记录节点数量
                if node.left:
                    queue.append(node.left)
                if node.right:
                    queue.append(node.right)
        return result

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

class Solution:
    def isBalanced(self, root: TreeNode) -> bool:
        st = []
        if not root:
            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
    
    def getDepth(self, cur):
        st = []
        if cur:
            st.append(cur)
        depth = 0
        result = 0
        while st:
            node = st.pop()
            if node:
                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()
                depth -= 1
            result = max(result, depth)
        return result

给定一个二叉树,返回所有从根节点到叶子节点的路径。

class Solution:
    def binaryTreePaths(self, root: TreeNode) -> List[str]:
        path=[]
        res=[]
        def backtrace(root, path):
            if not root:return 
            path.append(root.val)
            if (not root.left)and (not root.right):
               res.append(path[:])
            ways=[]
            if root.left:ways.append(root.left)
            if root.right:ways.append(root.right)
            for way in ways:
                backtrace(way,path)
                path.pop()
        backtrace(root,path)
        return ["->".join(list(map(str,i))) for i in res]

计算给定二叉树的所有左叶子之和。

class Solution:
    def sumOfLeftLeaves(self, root: TreeNode) -> int:
        """
        Idea: Each time check current node's left node. 
              If current node don't have one, skip it. 
        """
        stack = []
        if root: 
            stack.append(root)
        res = 0
        
        while stack: 
            # 每次都把当前节点的左节点加进去. 
            cur_node = stack.pop()
            if cur_node.left and not cur_node.left.left and not cur_node.left.right: 
                res += cur_node.left.val
                
            if cur_node.left: 
                stack.append(cur_node.left)
            if cur_node.right: 
                stack.append(cur_node.right)
                
        return res

给定一个二叉树,在树的最后一行找到最左边的值。

class Solution:
    def findBottomLeftValue(self, root: TreeNode) -> int:
        queue = deque()
        if root: 
            queue.append(root)
        result = 0
        while queue: 
            q_len = len(queue)
            for i in range(q_len): 
                if i == 0: 
                    result = queue[i].val 
                cur = queue.popleft()
                if cur.left: 
                    queue.append(cur.left)
                if cur.right: 
                    queue.append(cur.right)
        return result

给定一个二叉树和一个目标和,判断该树中是否存在根节点到叶子节点的路径,这条路径上所有节点值相加等于目标和。

class solution:
    def haspathsum(self, root: treenode, targetsum: int) -> bool:
        if not root: 
            return false

        stack = []  # [(当前节点,路径数值), ...]
        stack.append((root, root.val))

        while stack: 
            cur_node, path_sum = stack.pop()

            if not cur_node.left and not cur_node.right and path_sum == targetsum: 
                return true

            if cur_node.right: 
                stack.append((cur_node.right, path_sum + cur_node.right.val))    

            if cur_node.left: 
                stack.append((cur_node.left, path_sum + cur_node.left.val))

        return false
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值