mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 19:44:45 +08:00
Update 二叉树的递归遍历.md
This commit is contained in:
@ -115,7 +115,59 @@ void traversal(TreeNode* cur, vector<int>& vec) {
|
|||||||
|
|
||||||
|
|
||||||
Java:
|
Java:
|
||||||
|
```Java
|
||||||
|
// 前序遍历·递归·LC144_二叉树的前序遍历
|
||||||
|
class Solution {
|
||||||
|
ArrayList<Integer> preOrderReverse(TreeNode root) {
|
||||||
|
ArrayList<Integer> result = new ArrayList<Integer>();
|
||||||
|
preOrder(root, result);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
void preOrder(TreeNode root, ArrayList<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); // 注意这一句
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
Python:
|
Python:
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user