一:前序
/*** Definition for a binary tree node.* public 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;* }* }*/
class Solution {public List<Integer> preorderTraversal(TreeNode root) {List<Integer> list = new ArrayList<Integer>(); preorder(root,list);return list;}public void preorder(TreeNode root,List<Integer> list) {if (root == null) return;list.add(root.val);preorder(root.left,list);preorder(root.right,list);}
}
二:中序
/*** Definition for a binary tree node.* public 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;* }* }*/
class Solution {public List<Integer> inorderTraversal(TreeNode root) {List<Integer> list = new ArrayList<>();order(root,list);return list;}public void order(TreeNode node,List<Integer>list) {if (node == null) return ;order(node.left,list);list.add(node.val);order(node.right,list);}}
三:后序
/*** Definition for a binary tree node.* public 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;* }* }*/
class Solution {public List<Integer> postorderTraversal(TreeNode root) {List<Integer> list = new ArrayList<>();postorder(root,list);return list;}public void postorder(TreeNode root,List<Integer> list) {if (root == null) return;postorder(root.left,list);postorder(root.right,list);list.add(root.val); }}