双栈后序遍历树

双栈后序遍历树

class TreeNode {
     int val;
    TreeNode left;
      TreeNode right;
  TreeNode(int x) { val = x; }
  }

  //双栈后序遍历树
public class Test{
    Stack<TreeNode> stack1 = new Stack<TreeNode>();
      Stack<TreeNode> stack2 = new Stack<TreeNode>();
      public void postOrder(TreeNode root)
      {
          stack1.push(root);
          while(!stack1.isEmpty())
          {
              TreeNode pop = stack1.pop();
              stack2.push(pop);
              if(pop.left!=null)
                  stack1.push(pop.left);
              if(pop.right!=null)
                  stack1.push(pop.right);
          }
          while(!stack2.isEmpty())
          {
              System.out.println(stack2.pop().val+" ");
          }
      }
发布了22 篇原创文章 · 获赞 0 · 访问量 595

猜你喜欢

转载自blog.csdn.net/qq_44932835/article/details/105008703