二叉树的后序遍历

此博客链接:https://www.cnblogs.com/ping2yingshi/p/14092344.html

二叉树的后序遍历

题目链接:https://leetcode-cn.com/problems/binary-tree-postorder-traversal/

题目

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

示例:

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

2
/
3

输出: [3,2,1]

题解

思路:

     1.使用递归。

     2.使用迭代。二叉树的后序迭代算法和前序迭代是一样的,因为前序迭代是根左右,后序迭代是左右根,把前序迭代中左右换一下位置,然后倒序遍历就是后序遍历了,所以这里采用使用两个栈,先仿照前序遍历,遍历出结果为根右左的结果,然后放到栈中,重新取出就是后续遍历了。

代码

class Solution {
    public List<Integer> postorderTraversal(TreeNode root) {
        List <Integer> list=new ArrayList();
        if(root==null)
              return list;
        Stack<TreeNode> stack1=new Stack();
        Stack<Integer> stack2=new Stack();
        stack1.push(root);
        while(!stack1.isEmpty())
        {
            TreeNode temp=stack1.pop();
            stack2.push(temp.val);
              if(temp.left!=null)
              {
                   stack1.push(temp.left);
              }
               if(temp.right!=null)
              {
                   stack1.push(temp.right);
              }
        }
        while(!stack2.isEmpty())
        {
            list.add(stack2.pop());
        }
        return list;
    }
}

 结果

原文地址:https://www.cnblogs.com/ping2yingshi/p/14092344.html