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

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

示例:

输入: [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;
  }
}

发布了516 篇原创文章 · 获赞 1万+ · 访问量 123万+

猜你喜欢

转载自blog.csdn.net/hebtu666/article/details/104126909