题目地址: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. hbase参数调优

    @ 目录 HBase参数调优 hbase.regionserver.handler.count hbase.hregion.max.filesize hbase.hregion.majorcompac ...

  2. 使用GitHub Action进行打包并自动推送至OSS

    GitHub Action 是 GitHub 于 2018 年 10 月推出的一个 CI\CD 服务. 官方文档:https://docs.github.com/cn/actions CI\CD 持续 ...

  3. day03 部署NFS服务

    day03 部署NFS服务 NFS的原理 1.什么是NFS 共享网络文件存储服务器 2.NFS的原理 1.用户访问NFS客户端,将请求转化为函数 2.NFS通过TCP/IP连接服务端 3.NFS服务端 ...

  4. Android Handler 消息机制原理解析

    前言 做过 Android 开发的童鞋都知道,不能在非主线程修改 UI 控件,因为 Android 规定只能在主线程中访问 UI ,如果在子线程中访问 UI ,那么程序就会抛出异常 android.v ...

  5. iOS 的文件操作

    直接上操作 效果:将一张图片写入文件 (图片本身已经在Assets.xcassets里面了) 1.获取当前app的沙盒路径 NSString *documentPath = NSSearchPathF ...

  6. Linux基础命令---nslookup查询域名工具

    nslookup nslookup是一个查询DNS域名的工具,它有交互和非交互两种工作模式. 此命令的适用范围:RedHat.RHEL.Ubuntu.CentOS.Fedora.   1.语法     ...

  7. Output of C++ Program | Set 11

    Predict the output of following C++ programs. Question 1 1 #include<iostream> 2 using namespac ...

  8. entfrm-app赋能entfrm零代码开发平台 开启多平台分发

    entfrm-app是基于uni-app 框架.使用 Vue.js 语法开发的移动端 App开源产品.它可以编译为 H5.IOS App.Android App.微信小程序.QQ小程序.钉钉小程序.支 ...

  9. 【Python】【Module】json and pickle

    Python中用于序列化的两个模块 json     用于[字符串]和 [python基本数据类型] 间进行转换 pickle   用于[python特有的类型] 和 [python基本数据类型]间进 ...

  10. MySQL批量数据脚本示例

    一.建表 # 新建库 create database bigData; use bigData; #1 建表dept CREATE TABLE dept( id INT UNSIGNED PRIMAR ...