加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

【LeetCode每天一题】Binary Tree Preorder Traversal(前序遍历)

发布时间:2020-12-14 04:45:24 所属栏目:大数据 来源:网络整理
导读:Given a binary tree,return the?preorder?traversal of its nodes‘ values. Example: Input: [1,null,1,2,3 ] 1 2 / 3Output:?[1,3] Follow up:?Recursive solution is trivial,could you do it iteratively? ? 思路 二叉树的前序遍历方法分为递归法和使用

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

Example:

Input: [1,null,1,2,3 ]
1 2 / 3 Output:?[1,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,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)     # 遍历右节点

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读