二叉树的先序、中序、后序遍历
作者:互联网
输入{1,2,3}
输出
[[1,2,3],[2,1,3],[2,3,1]]
java
public class Solution {
/**
*
* @param root TreeNode类 the root of binary tree
* @return int整型二维数组
*/
List<Integer> front = new ArrayList<>();
List<Integer> mid = new ArrayList<>();
List<Integer> back = new ArrayList<>();
public int[][] threeOrders (TreeNode root) {
// write code here
PreorderTraversal(root);
InorderTraversal(root);
PostorderTraversal(root);
int[][] res = {
front.stream().mapToInt(Integer::valueOf).toArray(),
mid.stream().mapToInt(Integer::valueOf).toArray(),
back.stream().mapToInt(Integer::valueOf).toArray()
};
return res;
}
//前序遍历
public void PreorderTraversal(TreeNode root){
if(root == null)
return;
front.add(root.val);
PreorderTraversal(root.left);
PreorderTraversal(root.right);
}
//中序遍历
public void InorderTraversal(TreeNode root){
if(root == null)
return;
InorderTraversal(root.left);
mid.add(root.val);
InorderTraversal(root.right);
}
//后序遍历
public void PostorderTraversal(TreeNode root){
if(root == null)
return;
PostorderTraversal(root.left);
PostorderTraversal(root.right);
back.add(root.val);
}
}
标签:TreeNode,InorderTraversal,PreorderTraversal,中序,二叉树,return,root,public,先序 来源: https://blog.csdn.net/qq_37185361/article/details/113831946