給定一個二叉樹,返回它的 后序?遍歷。
示例:
輸入: [1,null,2,3] ?
? ?1
? ? \
? ? ?2
? ? /
? ?3?
輸出: [3,2,1]
進階:?遞歸算法很簡單,你可以通過迭代算法完成嗎?
思路:前序遍歷左右交換,然后倒序輸出
原因:前序:中左右,
我們左右交換遍歷:中右左
序列反過來:左右中=后序。
詳情請看:二叉樹遍歷
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode(int x) { val = x; }* }*/
class Solution {public List<Integer> postorderTraversal(TreeNode root) {LinkedList<TreeNode> stack = new LinkedList<>();LinkedList<Integer> output = new LinkedList<>();if (root == null)return output;stack.add(root);while (!stack.isEmpty()) {TreeNode node = stack.pollLast();output.addFirst(node.val);if (node.left != null)stack.add(node.left);if (node.right != null)stack.add(node.right);}return output;}
}