leetcode145. 二叉树的后序遍历 意想不到的骚操作
生活随笔
收集整理的這篇文章主要介紹了
leetcode145. 二叉树的后序遍历 意想不到的骚操作
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
給定一個(gè)二叉樹,返回它的 后序?遍歷。
示例:
輸入: [1,null,2,3] ?
? ?1
? ? \
? ? ?2
? ? /
? ?3?
輸出: [3,2,1]
進(jìn)階:?遞歸算法很簡(jiǎn)單,你可以通過迭代算法完成嗎?
思路:前序遍歷左右交換,然后倒序輸出
原因:前序:中左右,
我們左右交換遍歷:中右左
序列反過來(lái):左右中=后序。
詳情請(qǐng)看:二叉樹遍歷
/*** 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;} }總結(jié)
以上是生活随笔為你收集整理的leetcode145. 二叉树的后序遍历 意想不到的骚操作的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Nginx 配置TCP和UDP负载均衡
- 下一篇: MySQL常见的两种存储引擎:MyISA