当前位置:网站首页>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;
}
}
边栏推荐
猜你喜欢

编译预处理等细节

使用SuperMap iDesktopX数据迁移工具迁移地图文档和符号

树表的查找

北斗三号短报文终端露天矿山高边坡监测方案

正则表达式,匹配中间的某一段字符串

2022-08-04: Input: deduplicated array arr, the numbers in it only contain 0~9.limit, a number.Return: The maximum number that can be spelled out with arr if the requirement is smaller than limit.from

虚拟内存原理与技术

你要的七夕文案,已为您整理好!

Advanced Numbers_Review_Chapter 1: Functions, Limits, Continuity

shell statement to modify txt file or sh file
随机推荐
1873. The special bonus calculation
SuperMap iDesktop.Net之布尔运算求交——修复含拓扑错误复杂模型
22-07-31周总结
OpenGL 工作原理
C student management system Find student nodes based on student ID
leetcode-对称二叉树
627. 变更性别
转:查尔斯·汉迪:你是谁,比你做什么更重要
继承关系下构造方法的访问特点
dmp(dump)转储文件
HDU 1114: Piggy-Bank ← The Complete Knapsack Problem
View handler stepping record
C language implements a simple number guessing game
Industry case | insurance companies of the world's top 500 construction standards can be used to drive the business analysis system
torch.roll()
协作D2D局部模型聚合的半分散联合学习
1527. Patients suffering from a disease
HDU 1114:Piggy-Bank ← 完全背包问题
Common hardware delays
2022-08-04:输入:去重数组arr,里面的数只包含0~9。limit,一个数字。 返回:要求比limit小的情况下,能够用arr拼出来的最大数字。 来自字节。