二叉树的后序遍历

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_39360985/article/details/82902818

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

示例:

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

输出: [3,2,1]

进阶: 递归算法很简单,你可以通过迭代算法完成吗?

通过此题掌握二叉树的后序遍历,掌握Java泛型和栈的运用

题目分析:

二叉树的后序遍历,用递归遍历很容易实现,但如果用迭代算法就有一定的难度;

二叉树的后序遍历,顺序是——“左右根”(左子树,右子树,根节点),对于遍历,我们从根结点开始,访问到根结点时,先将它入栈,先进后出,满足了“左右根”,“根”在最后的要求;接下来我们访问到的是其右子树,后访问左子树。

我们在这里运用list的add()函数,每次都在“0”位置插入,list.add(0, node.val),先访问根结点,在0位置插入,后访问根节点的右子树,在0位置插入,在访问根节点的左子树,在0位置插入;这样最后的结果就是“左右根”

代码实现:

非递归:

public static class TreeNode
{
   int data;
   TreeNode left;
   TreeNode right;

   TreeNode(int val)
   {
       data = val;
   }
}

/**
* 非递归
*/
public List<Integer> postorderTraversal(TreeNode root)
{
   List<Integer> list = new ArrayList<>();
   Stack<TreeNode> stack = new Stack<>();

   if (root == null)
       return list;

   stack.push(root);

   while (!stack.isEmpty())
   {
       TreeNode node = stack.pop();

       list.add(0,node.data);

       if (node.left != null)
           stack.push(node.left);

       if (node.right != null)
           stack.push(node.right);

   }

   return list;
}

算法分析:

以主函数中构造的二叉树P为例:

    1
   / \
  2   3
 / \   \
4   5   6
  1. 将根节点1入栈;栈非空,node = stack.pop() = 1,在list的0位置插入1,此时list = [1];
  2. 根结点1的左孩子和右孩子非空,依次入栈,此时栈中的数据是:2,3
  3. 栈非空,node = stack.pop() = 3,在list的0位置插入3,此时list = [3,1];
  4. 节点3的左孩子为空,右孩子非空,将其右孩子6入栈,此时栈中的数据是:2,6
  5. 栈非空,node = stack.pop() = 6,在list的0位置插入6,此时list = [6,3,1]
  6. 结点6的左孩子和右孩子都为空,此时栈中的数据是:2
  7. 栈非空,node = stack.pop() = 2,在list的0位置插入2,此时list = [2,6,3,1]
  8. 结点2的左孩子和右孩子非空,依次入栈,此时栈中的数据是:4,5
  9. 栈非空,node = stack.pop() = 5,在list的0位置插入5,此时list = [5,2,6,3,1]
  10. 结点5的左孩子和右孩子都为空,此时栈中的数据是:4
  11. 栈非空,node = stack.pop() = 4,在list的0位置插入4,此时list = [4,5,2,6,3,1]
  12. 栈空,结束循环;
  13. 最后返回的结果就是:[4,5,2,6,3,1]

递归:

/**
*递归
*/
public List<Integer> postorderTraversal(TreeNode root)
{
   List<Integer> list = new ArrayList<>();

   if (root == null)
       return list;

   postorder(root,list);

   return list;
}

public static void postorder(TreeNode root, List list)
{
   if (root != null)
   {
       postorder(root.left,list);
       postorder(root.right,list);
       list.add(root.data);
   }
}

主函数:

public static void main(String[] args)
{
   TreeNode p = new TreeNode(1);
   p.left = new TreeNode(2);
   p.right = new TreeNode(3);
   p.left.left = new TreeNode(4);
   p.left.right = new TreeNode(5);
   p.right.right = new TreeNode(6);

   Tree14 t = new Tree14();

   List<Integer> list = t.postorderTraversal(p);
   for (int i = 0; i < list.size(); i++)
   {
       System.out.print(list.get(i) + " ");
   }

}

运行结果:

4 5 2 6 3 1

猜你喜欢

转载自blog.csdn.net/qq_39360985/article/details/82902818