zoukankan      html  css  js  c++  java
  • 【LeetCode每天一题】Binary Tree Preorder Traversal(前序遍历)

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

    Example:

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

    Follow up: Recursive solution is trivial, could you do it iteratively?

    思路


      二叉树的前序遍历方法分为递归法和使用循环辅助栈的方法,递归方法我们在递归左右节点之前先将当前节点的值添加进结果集中,然后进行递归。递归的结束条件是当节点为空时直接返回。循环辅助栈的方法就是我们申请一个栈,然后添加根节点到其中。执行循环遍历,最后循环体中我们先添加右节点,在添加左节点。每次弹出栈中最上面的节点。网栈为空时,循环结束。

    解决代码


     循环解决代码

     1 # Definition for a binary tree node.
     2 # class TreeNode(object):
     3 #     def __init__(self, x):
     4 #         self.val = x
     5 #         self.left = None
     6 #         self.right = None
     7 
     8 class Solution(object):
     9     def preorderTraversal(self, root):
    10         """
    11         :type root: TreeNode
    12         :rtype: List[int]
    13         """
    14         if not root:
    15             return []
    16         
    17         res = []          # 结果集
    18         stack = [root]      # 辅助栈
    19         while stack:          # 循环条件
    20             tem = stack.pop()     # 弹出最上层的节点
    21             if tem.right:          # 先判断当前节点的右节点
    22                 stack.append(tem.right)
    23             if tem.left:             # 在判断当前节点的左节点
    24                 stack.append(tem.left)
    25             res.append(tem.val)          # 将节点值添加进结果集中
    26         return res             # 返回结果集

     递归解决代码

     1 # Definition for a binary tree node.
     2 # class TreeNode(object):
     3 #     def __init__(self, x):
     4 #         self.val = x
     5 #         self.left = None
     6 #         self.right = None
     7 
     8 class Solution(object):
     9     def preorderTraversal(self, root):
    10         """
    11         :type root: TreeNode
    12         :rtype: List[int]
    13         """            
    14         if not root:      # 为空直接返回
    15             return 
    16         res = []
    17         self.tarversal(root, res)  # 开始递归
    18         return res
    19         
    20     def tarversal(self, root, res):
    21         if not root:        # 当前为空节点直接返回
    22             return
    23         res.append(root.val)      # 将当前节点的值添加进其中
    24         self.tarversal(root.left, res)      # 遍历左节点
    25         self.tarversal(root.right, res)     # 遍历右节点
  • 相关阅读:
    Educational Codeforces Round 64 (Rated for Div. 2)题解
    Codeforces Round #555 (Div. 3) F. Maximum Balanced Circle
    莫队算法总结
    cobalt strike使用笔记
    CMD命令行下载文件
    CTF线下赛AWD模式下的生存技巧
    python中multiprocessing模块
    密码重置
    python中的argparse模块
    python中BeautifulSoup模块
  • 原文地址:https://www.cnblogs.com/GoodRnne/p/10963509.html
Copyright © 2011-2022 走看看