怎样将网站建设后台装到云上,常用的oa系统办公软件,网站建设视频教程,有什么教做甜品的网站给定一个二叉树#xff0c;返回它的 后序 遍历。
示例:
输入: [1,null,2,3] 1 \ 2 / 3
输出: [3,2,1] 进阶: 递归算法很简单#xff0c;你可以通过迭代算法完成吗#xff1f;
思路#xff1a;前序遍历左右交换#xff0c;然后倒序输出
原因返回它的 后序 遍历。
示例:
输入: [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 ListInteger postorderTraversal(TreeNode root) {LinkedListTreeNode stack new LinkedList();LinkedListInteger 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;}
}