[leetcode]中级算法——树和图

这篇博客介绍了LeetCode中的几个中级算法问题,包括二叉树的锯齿遍历、从先序和中序遍历序列构造二叉树、填充同一层的兄弟节点、二叉搜索树中第K小的元素以及寻找岛屿的个数。通过代码实例展示了如何解决这些问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

二叉树的中序遍历

Given a binary tree, return the inorder traversal of its nodes' values.

Example:


Input: [1,null,2,3]
   1
    \
     2
    /
   3

Output: [1,3,2]

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 inorderTraversal(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        if not root:
            return []
        result = []
        result = result + self.inorderTraversal(root.left)
        result.append(root.val)
        result = result + self.inorderTraversal(root.right)
        return result

Code(others):


class Solution(object):
    def inorderTraversal(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        if not root:
            return []
        
        return self.inorderTraversal(root.left)+[root.val]+self.inorderTraversal(root.right)


二叉树的锯齿遍历

Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).

Example:

    3
   / \
  9  20
    /  \
   15   7
[
  [3],
  [20,9],
  [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 zigzagLevelOrder(self, root):
        """
        :type root: TreeNode
        :rtype: List[List[int]]
        """
        result = []
        if not root:
            return result
        stack = [root]
        time = 1
        while stack:
            temp = []
            nextCur = []
            nowCur = stack
            while nowCur:
                node = nowCur.pop()
                if node:
                    temp.append(node.val)
                    if time % 2 == 1:
                        nextCur.append(node.left)
                        nextCur.append(node.right)
                    else:
                        nextCur.append(node.right)
                        nextCur.append(node.left)
            time += 1
            if temp:
                result.append(temp)
            stack = nextCur
        return result
Code(others):
class Solution(object):
    def zigzagLevelOrder(self, root):
        """
        :type root: TreeNode
        :rtype: List[List[int]]
        """
        if not root:
            return []
        queue = [root]
        result = []
        order_flag = False
        while queue:
            size = len(queue)
            level = []
            for i in range(size):
                level.append(queue[i].val)
            for i in range(size):
                item = queue.pop(0)
                if item.left:
                    queue.append(item.left)
                if item.right:
                    queue.append(item.right)
            if order_flag:
                level.reverse()
            result.append(level)
            order_flag = not order_flag
        return result
总结:
可正常层次遍历之后再转置相应行。

从前序与中序遍历序列构造二叉树

Given preorder and inorder traversal of a tree, construct the binary tree.

Note:
You may assume that duplicates do not exist in the tree.

Example:

preorder = [3,9,20,15,7]
inorder = [9,3,15,20,7]

    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 buildTree(self, preorder, inorder):
        """
        :type preorder: List[int]
        :type inorder: List[int]
        :rtype: TreeNode
        """
        if not preorder:
            return None
        root = TreeNode(preorder[0])
        ids = inorder.index(preorder[0])
        root.left = self.buildTree(preorder[1:ids+1],inorder[0:ids])
        root.right = self.buildTree(preorder[ids+1:],inorder[ids+1:])
        return root
Code(others):
class Solution(object):
    def buildTree(self, preorder, inorder):
        """
        :type preorder: List[int]
        :type inorder: List[int]
        :rtype: TreeNode
        """
        d={}
        stack=[]
        for i,val in enumerate(inorder):
            d[val]=i
        root=parent=None
        for i in preorder:
            node=TreeNode(i)
            if not root:
                root=node
            elif d[i]<d[parent.val]:
                parent.left=node
                stack.append(parent)
            elif d[i]>d[parent.val]:
                while stack and d[stack[-1].val]<d[i]:
                    parent=stack.pop()
                parent.right=node
            parent=node
        return root
总结:
用哈希表和栈比递归效率要高

填充同一层的兄弟节点

Given a binary tree

struct TreeLinkNode {
  TreeLinkNode *left;
  TreeLinkNode *right;
  TreeLinkNode *next;
}

Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.

Initially, all next pointers are set to NULL.

Example:

Given the following perfect binary tree,

     1
   /  \
  2    3
 / \  / \
4  5  6  7

After calling your function, the tree should look like:

     1 -> NULL
   /  \
  2 -> 3 -> NULL
 / \  / \
4->5->6->7 -> NULL

Code(By myself):

# Definition for binary tree with next pointer.
# class TreeLinkNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
#         self.next = None

class Solution:
    # @param root, a tree link node
    # @return nothing
    def connect(self, root):
        if not root:
            return
        queue = [root]
        while queue:
            size = len(queue)
            leftNode = None
            for i in range(size):
                rightNode = queue.pop(0)
                if leftNode:
                    leftNode.next = rightNode
                leftNode = rightNode
                if rightNode.left:
                    queue.append(rightNode.left)
                if rightNode.right:
                    queue.append(rightNode.right)
            rightNode.next = None
Code(others):
class Solution:
    # @param root, a tree link node
    # @return nothing
    def connect(self, root):
        if root is None:
            return
        start = cur = root
        while start.left:
            while cur:
                cur.left.next = cur.right
                if cur.next:
                    cur.right.next = cur.next.left
                cur = cur.next
            cur = start.left
            start = start.left

二叉搜索树中第K小的元素

Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.

Note: 
You may assume k is always valid, 1 ≤ k ≤ BST's total elements.

Example:

Input: root = [3,1,4,null,2], k = 1
   3
  / \
 1   4
  \
   2
Output: 1

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 kthSmallest(self, root, k):
        """
        :type root: TreeNode
        :type k: int
        :rtype: int
        """
        s = []
        cur = root
        rank = 0
        while s or cur:
            if cur:
                s.append(cur)
                cur = cur.left
            else:
                cur = s.pop()
                rank += 1
                if rank == k:
                    return cur.val
                cur = cur.right

岛屿的个数

Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.

Example:

Input:
11110
11010
11000
00000

Output: 1

Code(By myself):

class Solution(object):
    def numIslands(self, grid):
        """
        :type grid: List[List[str]]
        :rtype: int
        """
        if grid is None:
            return None
        if grid == []:
            return 0
        self.n = len(grid)
        self.m = len(grid[0])
        number = 0
        for i in range(self.n):
            for j in range(self.m):
                if grid[i][j] == '1':
                    number += 1
                    self.change(grid,i,j)
        return number
    
    def change(self,grid,i,j):
        grid[i][j] = 0
        if i > 0 and grid[i-1][j] == '1':
            self.change(grid,i-1,j)
        if j > 0 and grid[i][j-1] == '1':
            self.change(grid,i,j-1)
        if i < self.n-1 and grid[i+1][j] == '1':
            self.change(grid,i+1,j)
        if j < self.m-1 and grid[i][j+1] == '1':
            self.change(grid,i,j+1)
Code(others):
class Solution(object):
    def numIslands(self, grid):
        """
        :type grid: List[List[str]]
        :rtype: int
        """
        if  not grid:
            return 0
        rows=len(grid)
        cols=len(grid[0])
        grids=[]
        grids.append([0]*(cols+2))
        for i in range(rows):
            grids.append([0]+grid[i]+[0])
        grids.append([0]*(cols+2))
        queue=[]
        n=0
        for i in range(1,rows+1):
            for j in range(1,cols+1):
                if grids[i][j]=='1' and ((i,j) not in queue):
                        if queue==[]:
                            queue.append((i,j))
                            while queue:
                                x,y=queue.pop(0)
                                grids[x][y]=0
                                if grids[x-1][y]=='1' and ((x-1,y) not in queue):
                                    queue.append((x-1,y))
                                if grids[x+1][y]=='1' and ((x+1,y) not in queue):
                                    queue.append((x+1,y))   
                                if grids[x][y-1]=='1' and ((x,y-1) not in queue):
                                    queue.append((x,y-1))
                                if grids[x][y+1]=='1' and ((x,y+1) not in queue):
                                    queue.append((x,y+1))
                            n+=1
                            
                            
        return n







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值