公共類——節(jié)點類代碼:
// 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 PreOrder {
public List<Integer> preorderTest(TreeNode root) {
List<Integer> res = new ArrayList<>();
preOrder(root, res);
return res;
}
public void preOrder(TreeNode root, List<Integer> res) {
if (root == null)
return;
//先打印當(dāng)前節(jié)點慈缔,然后打印左子樹叮称,最后再打印右子樹
res.add(root.val);
preOrder(root.left, res);
preOrder(root.right, res);
}
}
二、二叉樹的中序遍歷
class InOrder {
public List<Integer> inorderTest(TreeNode root) {
List<Integer> res = new ArrayList<>();
inOrder(root, res);
return res;
}
public void inOrder(TreeNode root, List<Integer> res) {
if(root == null) return;
inOrder(root.left, res);
res.add(root.val);
inOrder(root.right, res);
}
}
三藐鹤、二叉樹的后序遍歷
class PostOrder {
public List<Integer> postorderTest(TreeNode root) {
List<Integer> res = new ArrayList<>();
postOrder(root, res);
return res;
}
public void postOrder(TreeNode root, List<Integer> res){
if (root == null) return;
postOrder(root.left, res);
postOrder(root.right, res);
res.add(root.val);
}
}