当前位置:网站首页>Likou - preorder traversal, inorder traversal, postorder traversal of binary tree
Likou - preorder traversal, inorder traversal, postorder traversal of binary tree
2022-08-05 02:43:00 【qq_52025208】
一、题目描述:给你二叉树的根节点 root ,返回它节点值的 前序 遍历.
1.递归:
class Solution {
List<Integer> list = new ArrayList<>();
public List<Integer> preorderTraversal(TreeNode root) {
if(root == null) return list;
list.add(root.val);
preorderTraversal(root.left);
preorderTraversal(root.right);
return list;
}
}
2.非递归
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> list=new ArrayList<>();
if(root==null) return list;
Stack<TreeNode> stack=new Stack<>();
stack.push(root);
while(!stack.isEmpty()){
TreeNode node= stack.pop();
list.add(node.val);
if(node.right!=null){
stack.push(node.right);
}
if(node.left!=null){
stack.push(node.left);
}
}
return list;
}
}
二、中序遍历
递归:
class Solution {
List<Integer> list = new ArrayList<>();
public List<Integer> inorderTraversal(TreeNode root) {
if(root == null) return list;
inorderTraversal(root.left);
list.add(root.val);
inorderTraversal(root.right);
return list;
}
}
非递归:
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<>();
if(root == null) return list;
Stack<TreeNode> stack = new Stack<>();
while(root != null || !stack.empty()) {
while(root!= null) {
stack.push(root);
root = root.left;
}
root = stack.pop();
list.add(root.val);
root = root.right;
}
return list;
}
}
三、后序遍历
class Solution {
List<Integer> list = new ArrayList<>();
public List<Integer> postorderTraversal(TreeNode root) {
if(root == null) return list;
postorderTraversal(root.left);
postorderTraversal(root.right);
list.add(root.val);
return list;
}
}
边栏推荐
猜你喜欢

The 2022 EdgeX China Challenge will be grandly opened on August 3

从零到一快速学会三子棋

2022-08-04:输入:去重数组arr,里面的数只包含0~9。limit,一个数字。 返回:要求比limit小的情况下,能够用arr拼出来的最大数字。 来自字节。

学习笔记-----左偏树

树表的查找

What should I do if the self-incrementing id of online MySQL is exhausted?

【解密】OpenSea免费创造的NFT都没上链竟能出现在我的钱包里?

Simple implementation of YOLOv7 pre-training model deployment based on OpenVINO toolkit

特殊矩阵的压缩存储

【 2 】 OpenCV image processing: basic knowledge of OpenCV
随机推荐
Access Characteristics of Constructor under Inheritance Relationship
2022-08-04:输入:去重数组arr,里面的数只包含0~9。limit,一个数字。 返回:要求比limit小的情况下,能够用arr拼出来的最大数字。 来自字节。
QT语言文件制作
mysql tree structure query problem
torch.roll()
1667. 修复表中的名字
语法基础(变量、输入输出、表达式与顺序语句)
SuperMap支持的国产环境汇总
js中try...catch和finally的用法
【LeetCode刷题】-数之和专题(待补充更多题目)
Lexicon - the maximum depth of a binary tree
Access Characteristics of Constructor under Inheritance Relationship
正则表达式,匹配中间的某一段字符串
627. Change of gender
Data to enhance Mixup principle and code reading
Go 微服务开发框架 DMicro 的设计思路
Quickly learn chess from zero to one
Apache DolphinScheduler, a new generation of distributed workflow task scheduling platform in practice - Medium
The 20th day of the special assault version of the sword offer
leetcode 15