思路:
// @Title: 二叉树的中序遍历 (Binary Tree Inorder Traversal)
// @Author: qisiii
// @Date: 2022-03-01 21:20:28
// @Runtime: 0 ms
// @Memory: 39.6 MB
// @comment:
// @flag:
/**
* Definition for a binary tree node.
* public 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 {
public List<Integer> inorderTraversal(TreeNode root) {
if(root==null){
return new ArrayList();
}
List<Integer> zhong=new ArrayList();
zhong.addAll(inorderTraversal(root.left));
zhong.add(root.val);
zhong.addAll(inorderTraversal(root.right));
return zhong;
}
}
+++ title = “二叉树的中序遍历 (Binary Tree Inorder Traversal)” draft = false +++
思路:
// @Title: 二叉树的中序遍历 (Binary Tree Inorder Traversal)
// @Author: qisiii
// @Date: 2024-09-14 21:05:57
// @Runtime: 0 ms
// @Memory: 40.7 MB
// @comment:
// @flag:
/**
* Definition for a binary tree node.
* public 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 {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> result=new ArrayList<>();
sort(result,root);
return result;
}
private void sort(List<Integer> result,TreeNode node){
if(node!=null){
sort(result,node.left);
result.add(node.val);
sort(result,node.right);
}
}
}