后序遍历
- 迭代法
This commit is contained in:
whai 2024-01-16 19:31:42 +08:00
parent 5c7137c125
commit 7268302aec
3 changed files with 159 additions and 0 deletions

View File

@ -0,0 +1,77 @@
package cn.whaifree.leetCode.Tree;
import cn.whaifree.leetCode.model.TreeNode;
import org.junit.Test;
import java.util.*;
/**
* @version 1.0
* @Author whai文海
* @Date 2024/1/15 20:11
* @注释
*/
public class LeetCode145 {
@Test
public void test() {
TreeNode root = TreeNode.constructTree(new Integer[]{1, 2, 3, 4, 5});
root.printTree();
new Solution1().postorderTraversal(root).forEach(
System.out::println
);
}
class Solution {
List<Integer> res = new LinkedList<>();
public List<Integer> postorderTraversal(TreeNode root) {
if (root == null) {
return res;
}
postorder(root);
return res;
}
public void postorder(TreeNode root) {
if (root==null) return;
postorder(root.left);
postorder(root.right);
res.add(root.val);
}
}
class Solution1 {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> res = new LinkedList<Integer>();
if (root == null) {
return res;
}
Deque<TreeNode> stack = new ArrayDeque<>();
stack.push(root);
while (!stack.isEmpty()) {
TreeNode pop = stack.pop();
res.add(pop.val);
if (pop.left != null) {
stack.push(pop.left);
}
if (pop.right != null) {
stack.push(pop.right);
}
}
Collections.reverse(res);
return res;
}
}
}

View File

@ -0,0 +1,78 @@
package cn.whaifree.leetCode.Tree;
import cn.whaifree.leetCode.model.ListNode;
import cn.whaifree.leetCode.model.TreeNode;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
/**
* @version 1.0
* @Author whai文海
* @Date 2024/1/15 19:29
* @注释
*/
public class LeetCode94 {
@Test
public void test() {
TreeNode root = TreeNode.constructTree(new Integer[]{1, 2, 3, 4, 5});
TreeNode.printTree(root);
System.out.println(new Solution1().inorderTraversal(root));
}
class Solution {
List<Integer> res = new LinkedList<>();
public List<Integer> inorderTraversal(TreeNode root) {
if (root == null) {
return res;
}
inorder(root);
return res;
}
public void inorder(TreeNode root) {
if (root == null) {
return;
}
inorder(root.left);
res.add(root.val);
inorder(root.right);
}
}
class Solution1 {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> list = new LinkedList<Integer> ();
if (root == null) {
return list;
}
Deque<TreeNode> stack = new LinkedList<>();
TreeNode index = root;
while (!stack.isEmpty() || index != null) {
// 不断左边加入弹出获取右边的
// 每次循环处理一次节点左边右边和中间
if (index != null) {
stack.push(index);
index = index.left;
} else {
index = stack.pop();
list.add(index.val);
index = index.right;
}
}
return list;
}
}
}

View File

@ -55,6 +55,10 @@ public class TreeNode {
printNodeInternal(Collections.singletonList(root), 1, maxLevel);
}
public void printTree() {
printTree(this);
}
private static void printNodeInternal(List<TreeNode> nodes, int level, int maxLevel) {
if (nodes == null || nodes.isEmpty() || isAllElementsNull(nodes)) {
return;