【LeeCode】⼆叉树的序遍历

时间:2023-01-09 07:11:08

144.⼆叉树的前序遍历

【题目描述】

给你二叉树的根节点 ​root​ ,返回它节点值的 前序 遍历。

【示例】

【LeeCode】⼆叉树的序遍历

【代码】admin

package com.company;

import java.util.ArrayList;
import java.util.List;

class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {}
TreeNode(int val) { this.val = val; }
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}

class Solution {
List<Integer> list = new ArrayList<>();
public List<Integer> preorderTraversal(TreeNode root) {
// 前序: 根左右
if (root == null) return list;
preOrder(root);
return list;

}

public void preOrder(TreeNode root){
if (root == null) return;
list.add(root.val);
preOrder(root.left);
preOrder(root.right;
}
}

public class Test {
public static void main(String[] args) {

}
}

145.二叉树的后序遍历

【代码】admin

class Solution {
List<Integer> list = new ArrayList<>();
public List<Integer> postorderTraversal(TreeNode root) {
if (root == null) return list;
postOrder(root);
return list;
}
// 后序: 左右根
public void postOrder(TreeNode root){
if (root == null) return;

postOrder(root.left);
postOrder(root.right);
list.add(root.val);
}
}


94.⼆叉树的中序遍历

【代码】admin

class Solution {
List<Integer> list = new ArrayList<>();
public List<Integer> inorderTraversal(TreeNode root) {
if (root == null) return list;
postOrder(root);
return list;
}
// 中序: 左根右
public void postOrder(TreeNode root){
if (root == null) return;
postOrder(root.left);
list.add(root.val);
postOrder(root.right);

}
}



学习参考

​https://leetcode.cn/problems/binary-tree-preorder-traversal/solutions/461821/er-cha-shu-de-qian-xu-bian-li-by-leetcode-solution/​


​https://leetcode.cn/problems/binary-tree-preorder-traversal/solutions/87526/leetcodesuan-fa-xiu-lian-dong-hua-yan-shi-xbian-2/​