小言_互联网的博客

leetcode145. 二叉树的后序遍历 意想不到的骚操作

278人阅读  评论(0)

给定一个二叉树,返回它的 后序 遍历。

示例:

输入: [1,null,2,3]  
   1
    \
     2
    /
   3 

输出: [3,2,1]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?

思路:前序遍历左右交换,然后倒序输出

原因:前序:中左右,

我们左右交换遍历:中右左

序列反过来:左右中=后序。

详情请看:二叉树遍历


  
  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. class Solution {
  11. public List<Integer> postorderTraversal(TreeNode root) {
  12. LinkedList<TreeNode> stack = new LinkedList<>();
  13. LinkedList<Integer> output = new LinkedList<>();
  14. if (root == null) return output;
  15. stack.add(root);
  16. while (!stack.isEmpty()) {
  17. TreeNode node = stack.pollLast();
  18. output.addFirst(node.val);
  19. if (node.left != null)stack.add(node.left);
  20. if (node.right != null)stack.add(node.right);
  21. }
  22. return output;
  23. }
  24. }


转载:https://blog.csdn.net/hebtu666/article/details/104126909
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场