2021-08-21

Code 1

Question

Given the root of a binary tree, return the level order traversal of its nodes’ values. (i.e., from left to right, level by level).

Example 1

Input: root = [3,9,20,null,null,15,7]
Output: [[3],[9,20],[15,7]]

Example 2

Input: root = [1]
Output: [[1]]

Example 3

Input: root = []
Output: []

Solution

  • 广度优先搜索(BFS)
class Solution(object):
    def levelOrder(self, root):
        """
        :type root: TreeNode
        :rtype: List[List[int]]
        """
        if not root :
            return []
            
        queue=[root]
        l=[]
        
        while queue :
            row=[]
            for i in range(0,len(queue)) :
               q=queue.pop(0)
               row.append(q.val)
               if q.left :
                  queue.append(q.left)
               if q.right :
                  queue.append(q.right)
            l.append(row)
        return l

使用了队列,每次输出时队列中储存的都是一行的数据,用len()获取大小后循环输出。
注意这里用了dfs,以下是dfs

void bfs(TreeNode root) {
    
    
    Queue<TreeNode> queue = new ArrayDeque<>();
    queue.add(root);
    while (!queue.isEmpty()) {
    
    
        TreeNode node = queue.poll(); // Java 的 pop 写作 poll()
        if (node.left != null) {
    
    
            queue.add(node.left);
        }
        if (node.right != null) {
    
    
            queue.add(node.right);
        }
    }
}

但是这样遍历出来的是不分层的,我们这题要分层,所以做了一点点改动。

Code 2

Question

给定一个二叉树,找出其最大深度。

二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。

说明: 叶子节点是指没有子节点的节点。

示例:
给定二叉树 [3,9,20,null,null,15,7],

     3
   /   \
  9     20
 /        \
15         7

返回它的最大深度 3 。

Solution

  • 利用BFS(广度优先探索)
class Solution(object):
    def maxDepth(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if not root :
            return 0
        
        queue=[root]
        n=0
        
        
        while queue :
            for i in range(0,len(queue)) :
                q=queue.pop(0)
                if q.left :
                    queue.append(q.left)
                if q.right :
                    queue.append(q.right)
            n+=1
            
        return n
  • 利用DFS(深度优先探索)
class Solution(object):
    def maxDepth(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if not root :
            return 0
        else :
            lmax=self.maxDepth(root.left)
            rmax=self.maxDepth(root.right)
            return max(lmax,rmax)+1
  • 终止条件: 当前节点为空
  • 返回值:节点为空时返回 0。节点不为空时, 返回左右子树高度的最大值 + 1

Code 3

Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum.

A leaf is a node with no children.

Example 1

Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22
Output: true

Example 2

Input: root = [1,2,3], targetSum = 5
Output: false

Example

Input: root = [1,2], targetSum = 0
Output: false

Solution

  • 递归法(自己写的不太美观)
class Solution(object):
    def hasPathSum(self, root, targetSum):
        """
        :type root: TreeNode
        :type targetSum: int
        :rtype: bool
        """
        sum=0
        if not root :
            return False

        if root.val== targetSum :
            if root.left or root.right :
                return False
            else :
                return True
        
        return self.addSum(root,sum,targetSum)


    def addSum(self,root,sum,targetsum) :
        if not root:
            return False
        sum += root.val
        if sum == targetsum and not root.left and not root.right:
            return True
        else:
            return self.addSum(root.right,sum,targetsum) or self.addSum(root.left,sum,targetsum)

这样做的时候强行排除了很多乱七八糟的情况,感觉不太好。

  • 升级版递归
class Solution(object):
    def hasPathSum(self, root, targetSum):
        """
        :type root: TreeNode
        :type targetSum: int
        :rtype: bool
        """
        if not root :
            return False
        if not root.left and not root.right :
            return sum==root.val
        return self.hasPathSum(root.left,sum-root.val) or self.hasPathSum(root.right,sum-root.val)
  1. 改进 : 通过相减的想法更改targetsum的值,就不用重新写一个函数,避免了很多繁琐的检验。
  2. 这道题一定要注意是从“根到叶子”的距离,只有没有左右节点时才判断,不能中间取一段,而对于一个又是叶子又是根的节点是可以的。
  • 广度优先搜索(BFS)
class Solution(object):
	def hasPathSum(self, root, targetSum):
	    if not root :
	        return False
	    que_node=collections.deque([root])
	    que_val=collections.deque([root.val])
	    while que_node :
	        now=que_node.popleft()
	        temp=que_val.popleft()
    	    if not now.left and not now.right :
        	    if temp==targetSum :
            	    return True
           		continue
       	   if now.left :
        	    que_node.append(now.left)
        	    que_val.append(now.left.val+temp)
   	       if now.right :
           		que_node.append(now.right)
           		que_val.append(now.right.val+temp)
  	  	 return False

创建两个队列,一个储存节点,一个储存节点对应的值。当走到末尾且对应值为targetsum时,就返回True。如果一直不是targetsum,就返回False

Code 4

Question

Given the root of a binary tree, invert the tree, and return its root.

Example 1

Input: root = [4,2,7,1,3,6,9]
Output: [4,7,2,9,6,3,1]

Example 2

Input: root = [2,1,3]
Output: [2,3,1]

Example 3

Input: root = []
Output: []

Solution

  • 递归法(前、后序遍历)
class Solution(object):
    def invertTree(self, root):
        """
        :type root: TreeNode
        :rtype: TreeNode
        """
        if not root :
            return root

        #   root.left,root.right=root.right,root.left 加在这也行
        
        self.invertTree(root.left)
        self.invertTree(root.right)
        root.left,root.right=root.right,root.left
        
        return root
  1. 注意前序和后续可以,中序不行(中序会把一些节点交换两次)。
  2. 当前节点为空的时候,就返回。然后执行循环体,最后返回根节点。
  • 迭代法(BFS)
class Solution(object):
    def invertTree(self, root):
        """
        :type root: TreeNode
        :rtype: TreeNode
        """
        if not root :
            return root
        queue=[root]
        while queue :
            q=queue.pop()
            q.left,q.right=q.right,q.left
            if q.left :
                queue.append(q.left)
            if q.right :
                queue.append(q.right)
        return root

实际上就是层序遍历,稍微增加了一些步骤。

Code 5

Question

You are given the root of a binary search tree (BST) and an integer val.

Find the node in the BST that the node’s value equals val and return the subtree rooted with that node. If such a node does not exist, return null

Example1

Input: root = [4,2,7,1,3], val = 2
Output: [2,1,3]

Example 2

Input: root = [4,2,7,1,3], val = 5
Output: []

Solution

  • 迭代(BFS)
# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution(object):
    def searchBST(self, root, val):
        """
        :type root: TreeNode
        :type val: int
        :rtype: TreeNode
        """
        if not root :
            return root
        queue=[root]
        r=None

        while queue :
            q=queue.pop()
            if q.val==val :
                r=q
                break
            if q.left :
                queue.append(q.left)
            if q.right :
                queue.append(q.right)
    
        return r

这是自己的方法,明显复杂了TAT,思路局限在前几道题了。还有就是没有注意到这是二叉搜索树!!原来是有大小关系的呜呜。

  • 迭代(标准版)
class Solution(object):
    def searchBST(self, root, val):
        """
        :type root: TreeNode
        :type val: int
        :rtype: TreeNode
        """
        while root :
            if root.val >val :
                root=root.left
            elif root.val<val :
                root=root.right
            else :
                break
        return root
  • 递归
class Solution(object):
    def searchBST(self, root, val):
        """
        :type root: TreeNode
        :type val: int
        :rtype: TreeNode
        """
        if not root or root.val==val :
            return root

        if root.val<val :
            return self.searchBST(root.right,val)
        if root.val>val :
            return self.searchBST(root.left,val)

猜你喜欢

转载自blog.csdn.net/yxyxxxyyyy/article/details/119842615