訊息稱 LG 正開發三款全新蘋果顯示器,包括採用 Apple Silicon 晶片的 Pro Display XDR
阿新 • • 發佈:2021-12-19
給定一個二叉樹,返回它的 後序遍歷。
來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/binary-tree-postorder-traversal
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。
遞迴
import java.util.ArrayList; import java.util.List; class Solution { private List<Integer> ret = new ArrayList<>(); private void solve(TreeNode root) { if (root == null) { return; } solve(root.left); solve(root.right); ret.add(root.val); } public List<Integer> postorderTraversal(TreeNode root) { solve(root); return ret; } } class TreeNode { int val; TreeNode left; TreeNode right; TreeNode() { } TreeNode(int val) { this.val = val; } TreeNode(int val, TreeNode left, TreeNode right) { this.val = val; this.left = left; this.right = right; } }
棧
import java.util.*; class Solution { public List<Integer> postorderTraversal(TreeNode root) { List<Integer> res = new ArrayList<>(); if (root == null) { return res; } Stack<TreeNode> stack = new Stack<>(); TreeNode prev = null; while (root != null || !stack.isEmpty()) { while (root != null) { stack.push(root); root = root.left; } root = stack.pop(); if (root.right == null || root.right == prev) { res.add(root.val); prev = root; root = null; } else { stack.push(root); root = root.right; } } return res; } } class TreeNode { int val; TreeNode left; TreeNode right; TreeNode() { } TreeNode(int val) { this.val = val; } TreeNode(int val, TreeNode left, TreeNode right) { this.val = val; this.left = left; this.right = right; } }
Morris遍歷
心之所向,素履以往 生如逆旅,一葦以航import java.util.ArrayList; import java.util.List; class Solution { private List<Integer> ret = new ArrayList<>(); private TreeNode reverse(TreeNode root) { TreeNode pre = null, cur = root, next; while (cur != null) { next = cur.right; cur.right = pre; pre = cur; cur = next; } return pre; } private void getRightEdge(TreeNode root) { TreeNode head = reverse(root); TreeNode cur = head; while (cur != null) { ret.add(cur.val); cur = cur.right; } reverse(head); } public List<Integer> postorderTraversal(TreeNode root) { TreeNode cur = root; while (cur != null) { TreeNode mostRight = cur.left; if (mostRight != null) { while (mostRight.right != null && mostRight.right != cur) { mostRight = mostRight.right; } if (mostRight.right == null) { mostRight.right = cur; cur = cur.left; continue; } else { mostRight.right = null; getRightEdge(cur.left); } } cur = cur.right; } getRightEdge(root); return ret; } } class TreeNode { int val; TreeNode left; TreeNode right; TreeNode() { } TreeNode(int val) { this.val = val; } TreeNode(int val, TreeNode left, TreeNode right) { this.val = val; this.left = left; this.right = right; } }