题目地址: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)的更多相关文章

  1. C++版 - LeetCode 144. Binary Tree Preorder Traversal (二叉树先根序遍历,非递归)

    144. Binary Tree Preorder Traversal Difficulty: Medium Given a binary tree, return the preorder trav ...

  2. LeetCode: Binary Tree Preorder Traversal 解题报告

    Binary Tree Preorder Traversal Given a binary tree, return the preorder traversal of its nodes' valu ...

  3. [LeetCode] 144. Binary Tree Preorder Traversal 二叉树的先序遍历

    Given a binary tree, return the preorder traversal of its nodes' values. For example:Given binary tr ...

  4. 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 ...

  5. Java [Leetcode 144]Binary Tree Preorder Traversal

    题目描述: Given a binary tree, return the preorder traversal of its nodes' values. For example:Given bin ...

  6. 【LeetCode】94. Binary Tree Inorder Traversal 解题报告(Python&C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 解题方法 递归 迭代 日期 题目地址:https://leetcode.c ...

  7. 【LeetCode】589. N-ary Tree Preorder Traversal 解题报告 (Python&C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 递归 迭代 日期 题目地址:https://leetc ...

  8. leetcode 144. Binary Tree Preorder Traversal ----- java

    Given a binary tree, return the preorder traversal of its nodes' values. For example:Given binary tr ...

  9. (二叉树 递归) leetcode 144. Binary Tree Preorder Traversal

    Given a binary tree, return the preorder traversal of its nodes' values. Example: Input: [1,null,2,3 ...

随机推荐

  1. DIA技术及其软件工具介绍

    前言 关于蛋白质组学,你是不是已经听了太多公司的宣讲,介绍了一大堆的技术名词,反而越听越懵懂,脑袋一团乱麻?就和传话游戏一样,当我们接收了多手信息以后,得到的信息就越不准确.那么,何不自己看一看第一手 ...

  2. 在windows下使用shell,运行shell脚本

    在Windows操作系统下运行Shell脚本,缺少的只是一个Git软件.其下载路径为Git - Downloading Package. 安装之后,将安装路径下的bin文件夹的路径作为环境变量.于是我 ...

  3. MySQL8.0配置文件详解

    mysql8.0配置文件一.关键配置1. 配置文件的位置 MySQL配置文件 /etc/my.cnf 或者 /etc/my.cnf.d/server.cnf几个关键的文件:.pid文件,记录了进程id ...

  4. A Child's History of England.24

    Besides all these troubles, William the Conqueror was troubled by quarrels among his sons. He had th ...

  5. A Child's History of England.40

    Excommunication was, next to the Interdict I told you of at the close {end} of the last chapter, the ...

  6. 关于java中的安全管理器

    最近再查看java的源码的时候看见了这一类代码 final SecurityManager sm = System.getSecurityManager(); 想要了解这个是为了做什么,查看资料之后发 ...

  7. 2016广东工业大学新生杯决赛 A-pigofzhou的巧克力棒

    题目:GDUTOJ | pigofzhou的巧克力棒 (gdutcode.cn) 之前看了大佬博客的题解,一直没懂(我太菜了),后来听了朋友@77的讲解,终于懂了. 和拆分出2的n次方不一样,这是一种 ...

  8. 字符串属性转变List属性存入数据库

    项目中有系统IP字段,现将string转List存入数据库,每个功能块持久层实现方法不一样(分为jpa和mp) jpa: @Convert(converter = JpaConverterListJs ...

  9. Linux基础命令---dig工具

    dig dig是一个DNS查询工具,多数管理员会使用dig命令来解决DNS的问题. 此命令的适用范围:RedHat.RHEL.Ubuntu.CentOS.Fedora.   1.语法       di ...

  10. redis入门到精通系列(七):redis高级数据类型详解(BitMaps,HyperLogLog,GEO)

    高级数据类型和五种基本数据类型不同,并非新的数据结构.高级数据类型往往是用来解决一些业务场景. (一)BitMaps (1.1) BitMaps概述 在应用场景中,有一些数据只有两个属性,比如是否是学 ...