题解 | 实现二叉树先序,中序和后序遍历
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类 the root of binary tree
* @return int整型二维数组
*/
public void rootFront(TreeNode currentNode, StringBuffer sb) {
if (currentNode == null) return;
sb.append(currentNode.val + ",");
rootFront(currentNode.left, sb);
rootFront(currentNode.right, sb);
}
public void rootMiddle(TreeNode currentNode, StringBuffer sb) {
if (currentNode == null) return;
rootMiddle(currentNode.left, sb);
sb.append(currentNode.val + ",");
rootMiddle(currentNode.right, sb);
}
public void rootBack(TreeNode currentNode, StringBuffer sb) {
if (currentNode == null) return;
rootBack(currentNode.left, sb);
rootBack(currentNode.right, sb);
sb.append(currentNode.val + ",");
}
public int[][] threeOrders(TreeNode root) {
// write code here
if (root == null) {
return new int[3][0];
} else {
int[][] result = new int[3][];
StringBuffer fsb = new StringBuffer();
StringBuffer msb = new StringBuffer();
StringBuffer bsb = new StringBuffer();
rootFront(root, fsb);
rootMiddle(root, msb);
rootBack(root, bsb);
int[] fa = Arrays.stream(fsb.deleteCharAt(fsb.length() -
1).toString().split(",")).mapToInt(value -> Integer.valueOf(value)).toArray();
int[] ma = Arrays.stream(msb.deleteCharAt(msb.length() -
1).toString().split(",")).mapToInt(value -> Integer.valueOf(value)).toArray();
int[] ba = Arrays.stream(bsb.deleteCharAt(bsb.length() -
1).toString().split(",")).mapToInt(value -> Integer.valueOf(value)).toArray();
result[0] = fa;
result[1] = ma;
result[2] = ba;
return result;
}
}
}
其实遍历二叉树的递归写法大家都知道,这次主要提醒一下复制同样逻辑代码后相关变量要修改清楚。边复制边改,不然最后一次性改可能改漏。
