题意:
给你二叉树的根节点 root ,返回它节点值的 前(中,后)序 遍历。
数据范围:二叉树的节点数量满足 0 \le n \le 100 \0≤n≤100 ,二叉树节点的值满足 1 \le val \le 100 \1≤val≤100 ,树的各节点的值各不相同
示例:
输入:
{1,#,2,3}返回值:
[1,2,3]
题解:前序是根左右,中序是左根右,后序是左右根
1.递归写法
import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* public TreeNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @return int整型一维数组
*/
public void pp(List<Integer> list,TreeNode t)
{
if(t==null)
return ;
//前序
list.add(t.val);
pp(list,t.left);
pp(list,t.right);
//中序
/*
pp(list,t.left);
list.add(t.val);
pp(list,t.right);
*/
//后序
/*
pp(list,t.left);
pp(list,t.right);
list.add(t.val);
*/
}
public int[] preorderTraversal (TreeNode root) {
// write code here
ArrayList<Integer> a=new ArrayList<>();
pp(a,root);
int [] num=new int[a.size()];
for(int i=0;i<a.size();++i)
{
num[i]=a.get(i);
}
return num;
}
}
2.非递归写法,是用栈模拟函数递归调用的过程。
import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* public TreeNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @return int整型一维数组
*/
public int[] preorderTraversal (TreeNode root) {
// write code here
ArrayList<Integer> a=new ArrayList<>();
Stack<TreeNode> stack=new Stack<>();
if(root==null)
return new int [0];
stack.push(root);
//前序
while(!stack.empty())
{
TreeNode t=stack.pop();
a.add(t.val);
if(t.right!=null)
stack.push(t.right);
if(t.left!=null)
stack.push(t.left);
}
int [] num=new int[a.size()];
for(int i=0;i<a.size();++i)
{
num[i]=a.get(i);
}
return num;
}
}