程式碼隨想錄——二叉樹
阿新 • • 發佈:2022-12-10
二叉樹的遞迴遍歷
// 前序遍歷·遞迴·LC144_二叉樹的前序遍歷 class Solution { public List<Integer> preorderTraversal(TreeNode root) { List<Integer> result = new ArrayList<Integer>(); preorder(root, result); return result; } public void preorder(TreeNode root, List<Integer> result) { if (root == null) { return; } result.add(root.val); preorder(root.left, result); preorder(root.right, result); } } // 中序遍歷·遞迴·LC94_二叉樹的中序遍歷 class Solution { public List<Integer> inorderTraversal(TreeNode root) { List<Integer> res = new ArrayList<>(); inorder(root, res); return res; } void inorder(TreeNode root, List<Integer> list) { if (root == null) { return; } inorder(root.left, list); list.add(root.val); // 注意這一句 inorder(root.right, list); } } // 後序遍歷·遞迴·LC145_二叉樹的後序遍歷 class Solution { public List<Integer> postorderTraversal(TreeNode root) { List<Integer> res = new ArrayList<>(); postorder(root, res); return res; } void postorder(TreeNode root, List<Integer> list) { if (root == null) { return; } postorder(root.left, list); postorder(root.right, list); list.add(root.val); // 注意這一句 } }