【LeetCode】144. Binary Tree Preorder Traversal 解题报告(Python&C++&Java)
- 作者: 负雪明烛
- id: fuxuemingzhu
- 个人博客:http://fuxuemingzhu.cn/
题目地址:https://leetcode.com/problems/binary-tree-preorder-traversal/#/description
题目描述
Given a binary tree, return the preorder traversal of its nodes’ values.
For example:
Given binary tree {1,#,2,3},
1
\
2
/
3
return [1,2,3].
Note: Recursive solution is trivial, could you do it iteratively?
题目大意
求一个二叉树的先序遍历。
解题方法
递归
递归的思路就是先保存根节点的值,然后递归左子树和右子树。
python代码如下:
# 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 preorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if not root: return []
res = []
res.append(root.val)
res.extend(self.preorderTraversal(root.left))
res.extend(self.preorderTraversal(root.right))
return res
Java代码如下:
public class Solution {
List<Integer> ans = new ArrayList<Integer>();
public List<Integer> preorderTraversal(TreeNode root) {
preOrder(root);
return ans;
}
public void preOrder(TreeNode root){
if(root == null){
return;
}
ans.add(root.val);
preOrder(root.left);
preOrder(root.right);
}
}
C++代码如下:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> res;
preorder(root, res);
return res;
}
void preorder(TreeNode* root, vector<int>& res) {
if (!root) return;
res.push_back(root->val);
preorder(root->left, res);
preorder(root->right, res);
}
};
迭代
迭代版本的需要使用栈,先把右孩子进栈,再左孩子进栈。
为什么这个访问顺序呢?我们知道栈是后进先出的数据结构,所以遍历完根节点之后,把右孩子放到栈里,把左孩子放到栈里,那么下一次在出栈的时候是左孩子,所以总之就是个根-->左-->右先序遍历的过程了。
Python代码如下:
# 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 preorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if not root: return []
res = []
stack = []
stack.append(root)
while stack:
node = stack.pop()
if not node:
continue
res.append(node.val)
stack.append(node.right)
stack.append(node.left)
return res
Java代码如下:
public class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
if(root == null){
return new ArrayList<Integer>();
}
List<Integer> ans = new ArrayList<Integer>();
Stack<TreeNode> stack = new Stack<TreeNode>();
stack.push(root);
while(!stack.isEmpty()){
TreeNode temp = stack.pop();
ans.add(temp.val);
if(temp.right != null){
stack.push(temp.right);
}
if(temp.left != null){
stack.push(temp.left);
}
}
return ans;
}
}
C++代码如下:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> res;
stack<TreeNode*> s;
s.push(root);
while (!s.empty()) {
auto node = s.top(); s.pop();
if (!node) continue;
res.push_back(node->val);
s.push(node->right);
s.push(node->left);
}
return res;
}
};
日期
2017 年 5 月 20 日
2019 年 1 月 25 日 —— 这学期最后一个工作日
2019 年 9 月 20 日 —— 是选择中国互联网式加班?还是外企式养生?
【LeetCode】144. Binary Tree Preorder Traversal 解题报告(Python&C++&Java)的更多相关文章
- C++版 - LeetCode 144. Binary Tree Preorder Traversal (二叉树先根序遍历,非递归)
144. Binary Tree Preorder Traversal Difficulty: Medium Given a binary tree, return the preorder trav ...
- LeetCode: Binary Tree Preorder Traversal 解题报告
Binary Tree Preorder Traversal Given a binary tree, return the preorder traversal of its nodes' valu ...
- [LeetCode] 144. Binary Tree Preorder Traversal 二叉树的先序遍历
Given a binary tree, return the preorder traversal of its nodes' values. For example:Given binary tr ...
- Java for LeetCode 144 Binary Tree Preorder Traversal
Given a binary tree, return the preorder traversal of its nodes' values. For example: Given binary t ...
- Java [Leetcode 144]Binary Tree Preorder Traversal
题目描述: Given a binary tree, return the preorder traversal of its nodes' values. For example:Given bin ...
- 【LeetCode】94. Binary Tree Inorder Traversal 解题报告(Python&C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 解题方法 递归 迭代 日期 题目地址:https://leetcode.c ...
- 【LeetCode】589. N-ary Tree Preorder Traversal 解题报告 (Python&C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 递归 迭代 日期 题目地址:https://leetc ...
- leetcode 144. Binary Tree Preorder Traversal ----- java
Given a binary tree, return the preorder traversal of its nodes' values. For example:Given binary tr ...
- (二叉树 递归) leetcode 144. Binary Tree Preorder Traversal
Given a binary tree, return the preorder traversal of its nodes' values. Example: Input: [1,null,2,3 ...
随机推荐
- MYSQL5.8-----4
cc
- 基本绘图函数:plot的使用
注意:"##"后面是程序输出结果 例如: par("bg") # 命令 ## [1] "white" # 结果 基本绘图函数: plot:散 ...
- C#筛选项联动,联动筛选
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { FillDep(); } // FillDG(); ...
- day34 前端基础之JavaScript
day34 前端基础之JavaScript ECMAScript 6 尽管 ECMAScript 是一个重要的标准,但它并不是 JavaScript 唯一的部分,当然,也不是唯一被标准化的部分.实际上 ...
- 【swift】CoreData Crash(崩溃)(Failed to call designated initializer on NSManagedObject class)
感谢另一篇博客:https://blog.csdn.net/devday/article/details/6577985 里面的图片和介绍,发现问题如他描述的一样,没有bundle 我的Xcode版本 ...
- Android: EditText设置属性和设置输入规则
1.EditText输入限制规则 在xml:EditText 设置属性 android:digits="ABCDE123&*" ABCDE123&*是你的限制规则 ...
- springboot热部署与监控
一.热部署 添加依赖+Ctrl+F9 <dependency> <groupId>org.springframework.boot</groupId> <ar ...
- Linux系统分区及挂载点
一.关于Linux的分区情况 虽然硬盘分区表中最多能存储四个分区,但我们实际使用时一般只分为两个分区,一个是主分区(Primary Partion)一个是扩展分区(extended partition ...
- 2.8 rust 枚举与模式匹配
Enums and Pattern Matching 摘要 枚举定义 enum IpAddrKind { V4, V6, } 枚举方法 fn main() { enum Message { Quit, ...
- Spring Boot中使用Servlet与Filter
在Spring Boot中使用Servlet,根据Servlet注册方式的不同,有两种使用方式.若使用的是Servlet3.0+版本,则两种方式均可使用:若使用的是Servlet2.5版本,则只能使用 ...