DESC:
题目描述
分别按照二叉树先序,中序和后序打印所有的节点。
示例1
输入
{1,2,3}返回值
[[1,2,3],[2,1,3],[2,3,1]]备注:
n≤106n \leq 10^6n≤106
CODE:
import java.util.*; /* * public class TreeNode { * int val = 0; * TreeNode left = null; * TreeNode right = null; * } */ public class Solution { /** * * @param root TreeNode类 the root of binary tree * @return int整型二维数组 */ public int[][] threeOrders (TreeNode root) { // write code here if (root == null) { return null; } List<Integer> preList = new ArrayList(); List<Integer> milList = new ArrayList(); List<Integer> aftList = new ArrayList(); find(root, preList, milList, aftList); int[] preArr = trans(preList); int[] milArr = trans(milList); int[] aftArr = trans(aftList); return new int[] []{preArr, milArr, aftArr}; } public void find (TreeNode node, List<Integer> preList, List<Integer> milList, List<Integer> aftList) { if (node == null) { return; } preList.add(node.val); find(node.left, preList, milList, aftList); milList.add(node.val); find(node.right, preList, milList, aftList); aftList.add(node.val); } public int[] trans (List<Integer> list) { int[] arr = new int[list.size()]; for (int i = 0; i < list.size(); i++) { arr[i] = list.get(i); } return arr; } }
Python (前序):
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]: res = [] self.solve(root, res) return res def solve(self, node:TreeNode, res:List[int]) -> List[int]: if not node: return res.append(node.val) self.solve(node.left, res) self.solve(node.right, res)
NOTES:
- 递归,前序、中序、后序在递归的区别就在当前节点值添加的时机或先后顺序问题
- 左右子树都通过递归获取,前序话就最先添加当前节点值,中序就放在左右子树递归中间,后序就放在左右子树递归完成后添加。