LeetCode:二叉树前中后序遍历
1.思路
前中后序的遍历采用递归法,递归三部曲(确定递归函数参数及其返回值、确定终止条件、确定单层递归的顺序)已经内化,happy~
2.代码实现
//前序遍历
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
// 中 - 左 - 右
List<Integer> list = new ArrayList<>();
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);
}
}
// 中序遍历
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<>();
inorder(root, list);
return list;
}
public void inorder(TreeNode root, List<Integer> list) {
if (root == null) {
return;
}
inorder(root.left, list);
list.add(root.val);
inorder(root.right, list);
}
}
// 后序遍历
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);
}
}
3.复杂度分析
时间复杂度:(n).
空间复杂度:O(n).
// 层序(前序)遍历,很清晰
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<>();
if (root == null) {
return list;
}
Stack<TreeNode> stack = new Stack<>();
stack.add(root);
while (!stack.isEmpty()) {
TreeNode temp = stack.pop();
list.add(temp.val);
if (temp.right != null) {
stack.add(temp.right);
}
if (temp.left != null) {
stack.add(temp.left);
}
}
return list;
}
}
// 后序,在前序的基础上反转一下左右节点入栈顺序,目标是左右中,前序是中左右,将前序改为中右左,最后结果即可
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<>();
if (root == null) {
return list;
}
Stack<TreeNode> stack = new Stack<>();
// 后序:左 -> 右 -> 中
stack.push(root);
while (!stack.isEmpty()) {
TreeNode temp = stack.pop();
list.add(temp.val);
if (temp.left != null) {
stack.push(temp.left);
}
if (temp.right != null) {
stack.push(temp.right);
}
}
Collections.reverse(list);
return list;
}
}