Leetcode 98、102与107

Leetcode 98、102与107

二叉树遍历

二叉树遍历共有前序、中序、后序与层次四种遍历,其中前三种以根出现的位置区分:

前序遍历:根->左->右
中序遍历:左->根->右
后序遍历:左->右->根

而层次是从根到子节点最后到叶子结点的层序遍历方法,具体以leetcode 102和107为例。

Leetcode 102

  • 问题描述如下:

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

For example:
Given binary tree [3,9,20,null,null,15,7],
    3
   / \
  9  20
    /  \
   15   7
return its level order traversal as:
[
  [3],
  [9,20],
  [15,7]
]
  • 思路:我们用一个队列保存头层结点,遍历一层,一边取值一边添加子结点,取完即可。

  • 代码如下:

class Solution:
    def levelOrder(self, root):
        if not root: return []
        res = []
        queue = [root]
        while queue:
            tmp = []
            size = len(queue)
            while size > 0:
                node = queue.pop(0)
                tmp.append(node.val)
                if node.left: queue.append(node.left)
                if node.right: queue.append(node.right)
                size -= 1
            res.append(tmp)
        return res
                

Leetcode 107

  • 问题描述如下:

Given a binary tree, return the bottom-up level order traversal of its nodes’ values. (ie, from left to right, level by level from leaf to root).

For example:
Given binary tree [3,9,20,null,null,15,7],
    3
   / \
  9  20
    /  \
   15   7
return its bottom-up level order traversal as:
[
  [15,7],
  [9,20],
  [3]
]
  • 思路:与102一致,最后逆向输出。
  • 代码如下:
class Solution:
    def levelOrderBottom(self, root):
        if not root: return []
        ans = []
        queue = [root]
        while queue:
            size = len(queue)
            tmp = []
            while size > 0:
                node = queue.pop(0)
                tmp.append(node.val)
                if node.left: queue.append(node.left)
                if node.right: queue.append(node.right)
                size -= 1
            ans.append(tmp)
        return ans[::-1]
        

Leetcode 98

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 1:

Input:
    2
   / \
  1   3
Output: true
Example 2:

    5
   / \
  1   4
     / \
    3   6
Output: false
  • 思路如下:用中序遍历,用一个标签记录上一个结点,如果上一个结点的值大于等于正在遍历的结点,则返回False。
  • 代码如下:
class Solution:
    def isValidBST(self, root):
        if root is None: 
            return True
        stack = []
        pre = None
        while stack or root:
            while root:
                stack.append(root)
                root = root.left
            root = stack.pop()
            if pre and pre.val >= root.val: return False
            pre = root
            root = root.right
        return True
发布了89 篇原创文章 · 获赞 37 · 访问量 9万+

猜你喜欢

转载自blog.csdn.net/u012891055/article/details/85174596
今日推荐