给定一个二叉树的根节点 root
,返回 它的 中序 遍历
import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
public class Solution94 {
//TreeNode类
public static 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;
}
}
//层次反序列化就是根据给的数组来重新创建二叉树
public static TreeNode generateTreeNode(String treeStr) {
//System.out.println("111");
String[] strs = treeStr.substring(1, treeStr.length() - 1).split(",");
Integer[] nums = new Integer[strs.length];
for (int i = 0; i < strs.length; i++) {
if ("null".equals(strs[i])) {
nums[i] = null;
} else {
nums[i] = Integer.parseInt(strs[i]);
}
}
//for(int i=0;i<nums.length;i++) System.out.println(nums[i]);
if (nums == null || nums.length == 0) {
return null;
}
int len = nums.length;
int index = 0;
TreeNode head = new TreeNode(nums[index]);
Deque<TreeNode> nodeQueue = new LinkedList<>();
nodeQueue.offer(head);
TreeNode cur;
while (index < len) {
index++;
if (index >= len) {
System.out.println(head.val);
return head;
}
cur = nodeQueue.poll();
Integer left = nums[index];
if (left != null) {
cur.left = new TreeNode(left);
nodeQueue.offer(cur.left);
}
index++;
if (index >= len) {
return head;
}
Integer right = nums[index];
if (right != null) {
cur.right = new TreeNode(right);
nodeQueue.offer(cur.right);
}
//index++;
}
//System.out.println(head.val);
return head;
}
public static void main(String[] args) {
//调用反序列化方法来生成一棵树
TreeNode tmp=generateTreeNode("[3,9,20,null,null,15,7]");
//调用中序遍历的方法
inorferTraversal(tmp);
}
//中序遍历方法
public static List<Integer> inorferTraversal(TreeNode root){
List<Integer> res=new ArrayList<>();
if(root!=null)
//递归实现中序遍历
f(res,root);
return res;
}
public static void f(List<Integer>res, TreeNode head){
if(head==null){
return;
}
f(res,head.left);
System.out.println(head.val);
res.add(head.val);
f(res,head.right);
}
}
注意调用不同类里的publc方法要先new对象,通过对象调用
不带static的方法称为实例方法,实例方法的调用必须先new对象。