二叉樹後序遍曆非遞迴實現

來源:互聯網
上載者:User

二叉樹的先序,中序遍曆的非遞迴遍曆方法比較簡單,只要藉助一個棧就可以很容易實現。但其後序遍曆就有些複雜了,這裡借鑒下面這篇文章中的後序非遞迴遍曆演算法。http://blog.csdn.net/xingzhemoluo/article/details/40898233

利用兩個棧來實現後序遍曆,一個棧用於儲存遍曆結果,另一個棧作為一個輔助棧。

/*二叉樹後序非遞迴遍曆    * 藉助兩個棧可以用很簡單的方式實現二叉樹的後序非遞迴遍曆    * */    public static void postOrder(TreeNode root){        if (root == null){            return;        }        Stack<TreeNode> stack = new Stack<TreeNode>();        Stack<TreeNode> output = new Stack<TreeNode>();        TreeNode p = root;        while (p != null || !stack.isEmpty()){            if (p != null){                stack.push(p);                output.push(p);                p = p.right;            }else{                p = stack.pop();                p = p.left;            }        }        while (!output.isEmpty()){            System.out.println(output.pop().val + " ");        }    }
public class TreeNode {    public int val;    public TreeNode left;    public TreeNode right;    public TreeNode(int x){        this.val = x;    }}



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.