[leetcode]初级算法——树

这篇博客详细探讨了LeetCode中与二叉树相关的算法问题,包括二叉树的最大深度、验证二叉搜索树、对称二叉树的判断以及将有序数组转换为二叉搜索树。博主提供了自我实现的代码示例,涵盖了递归和非递归的解决方案,有助于读者理解和掌握这些算法。
摘要由CSDN通过智能技术生成

二叉树的最大深度

Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

Note: A leaf is a node with no children.

Example:

    3
   / \
  9  20
    /  \
   15   7

Code(By myself):

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None


class Solution(object):
    def maxDepth(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if (not root):
            return 0
        leftDepth = self.maxDepth(root.left) + 1
        rightDepth = self.maxDepth(root.right) + 1
        return max(leftDepth,rightDepth)

Code(others):

class Solution(object):
    def maxDepth(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if root is None:
            return 0
        return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))

总结:

递归求解

验证二叉搜索数

Given a binary tree, determine if it is a valid binary search tree (BST).

Assume a BST is defined as follows:

  • The left subtree of a node contains only nodes with keys less than the node's key.
  • The right subtree of a node contains only nodes with keys greater than the node's key.
  • Both the left and right subtrees must also be binary search trees.

Example:

Input:
    2
   / \
  1   3
Output: true

Code(By myself):

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def isValidBST(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        if (not root):
            return True
        def maxLeft(lroot):
            while lroot.right:
                lroot = lroot.right
            return lroot.val
            
        def minRight(rroot):
            while rroot.left:
                rroot = rroot.left
            return rroot.val
        
        left = -float('inf')
        right = float('inf')
        
        if root.left:
            left = maxLeft(root.left)
        if root.right:
            right = minRight(root.right)
            
        if self.isValidBST(root.left) and self.isValidBST(root.right):
            if left < root.val and root.val < right:
                return True
            else:
                return False
        else:
            return False
Code(others):
class Solution(object):
    
    
    def validBST(self, root, min, max):
        if root == None:
            return True
        if root.val <= min or root.val >= max:
            return False
        return self.validBST(root.left, min, root.val) and self.validBST(root.right, root.val, max)
    
    def isValidBST(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        return self.validBST(root, -21474836480, 21474836470)
总结:

可以将root.val当成左子树的最大值右子树的最小值

对称二叉树

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

Example:

    1
   / \
  2   2
 / \ / \
3  4 4  3

Code(By myself):

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def isSymmetric(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        if root == None:
            return True
        return self.compare(root.left, root.right)
    
    def compare(self, left, right):
        if left == None and right == None:
            return True
        elif left and right:
            return self.compare(left.right, right.left) and self.compare(left.left, right.right) and left.val == right.val
        else:
            return False
Code(others):
class Solution(object):
    def isSymmetric(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        if not root:
            return True
        q = []
        q.append((root.left, root.right))
        while q:
            l, r = q.pop()
            if not l and not r:
                continue
            if not l and r:
                return False
            if l and not r:
                return False
            if l.val != r.val:
                return False
            q.append((l.left, r.right))
            q.append((l.right, r.left))
        return True

总结:

  1. 递归求解
  2. 利用队列求解

对称二叉树

Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).

Example:

    3
   / \
  9  20
    /  \
   15   7
return its level order traversal as:
[
  [3],
  [9,20],
  [15,7]
]

Code(By myself):

class Solution(object):
    def levelOrder(self, root):
        """
        :type root: TreeNode
        :rtype: List[List[int]]
        """
        result = []
        if root == None:
            return result
        
        q = [root]
        
        while q:
            p = q
            q = []
            levelResult = []
            while p:
                r = p.pop(0)
                levelResult.append(r.val)
                if r.left:
                    q.append(r.left)
                if r.right:
                    q.append(r.right)
            result.append(levelResult)
        return result
Code(others):
class Solution(object):
    def levelOrder(self, root):
        """
        :type root: TreeNode
        :rtype: List[List[int]]
        """
        res = []
        self.dfs(root, 0, res)
        return res

    def dfs(self, root, depth, res):
        if root == None:
            return res
        if len(res) < depth+1:
            res.append([])
        res[depth].append(root.val)
        self.dfs(root.left, depth+1, res)
        self.dfs(root.right, depth+1, res)
总结:

  1. 双层循环加队列实现层次遍历
  2. 添加depth标识符利用递归实现层次遍历

将有序数组转换为二叉搜索树

Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

Example:

Given the sorted array: [-10,-3,0,5,9],

One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:

      0
     / \
   -3   9
   /   /
 -10  5

Code(By myself):

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def sortedArrayToBST(self, nums):
        """
        :type nums: List[int]
        :rtype: TreeNode
        """
        if len(nums) == 0:
            return None
        root = TreeNode(nums[len(nums)//2])
        if len(nums) == 1:
            return root
        else:
            root.left = self.sortedArrayToBST(nums[:len(nums)//2])
            root.right = self.sortedArrayToBST(nums[len(nums)//2+1:])
            return root
Code(others):
class Solution(object):
    def sortedArrayToBST(self, nums):
        """
        :type nums: List[int]
        :rtype: TreeNode
        """
        size = len(nums)
        if size == 0:
            return None
        if size == 1:
            return TreeNode(nums[0])
        size = size//2
        root = TreeNode(nums[size])
        root.left = self.sortedArrayToBST(nums[:size])
        root.right = self.sortedArrayToBST(nums[size+1:])
        return root





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值