Skip to content

Instantly share code, notes, and snippets.

@zhanglintc
Last active September 29, 2020 02:25
Show Gist options
  • Save zhanglintc/2d1b4d5f92090516541d0cc5b76d10d4 to your computer and use it in GitHub Desktop.
Save zhanglintc/2d1b4d5f92090516541d0cc5b76d10d4 to your computer and use it in GitHub Desktop.
preorderTraversal, inorderTraversal, postorderTraversal
// 二叉树前中后序遍历统一写法:
// https://leetcode-cn.com/problems/binary-tree-postorder-traversal/solution/bang-ni-dui-er-cha-shu-bu-zai-mi-mang-che-di-chi-t/
class Solution {
// 前序遍历
public List<Integer> preorderTraversal(TreeNode root) {
if (root == null) return new LinkedList<>();
List<Integer> res = new LinkedList<>();
Stack<TreeNode> st = new Stack<>();
st.push(root);
while (!st.isEmpty()) {
TreeNode node = st.pop();
if (node != null) {
if (node.right != null) st.push(node.right); // 右
if (node.left != null) st.push(node.left); // 左
st.push(node); // 中
st.push(null);
}
else {
res.add(st.pop().val);
}
}
return res;
}
// 中序遍历
public List<Integer> inorderTraversal(TreeNode root) {
if (root == null) return new LinkedList<>();
List<Integer> res = new LinkedList<>();
Stack<TreeNode> st = new Stack<>();
st.push(root);
while (!st.isEmpty()) {
TreeNode node = st.pop();
if (node != null) {
if (node.right != null) st.push(node.right); // 右
st.push(node); // 中
st.push(null);
if (node.left != null) st.push(node.left); // 左
}
else {
res.add(st.pop().val);
}
}
return res;
}
// 后序遍历
public List<Integer> postorderTraversal(TreeNode root) {
if (root == null) return new LinkedList<>();
List<Integer> res = new LinkedList<>();
Stack<TreeNode> st = new Stack<>();
st.push(root);
while (!st.isEmpty()) {
TreeNode node = st.pop();
if (node != null) {
st.push(node); // 中
st.push(null);
if (node.right != null) st.push(node.right); // 右
if (node.left != null) st.push(node.left); // 左
}
else {
res.add(st.pop().val);
}
}
return res;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment