Binary Tree Postorder Traversal

來源:互聯網
上載者:User

標籤:java   leetcode   tree   

題目

Given a binary tree, return the postorder traversal of its nodes‘ values.

For example:
Given binary tree {1,#,2,3},

   1         2    /   3

return [3,2,1].

Note: Recursive solution is trivial, could you do it iteratively?

方法
/** * 要保證根結點在左孩子和右孩子訪問之後才能訪問,因此對於任一結點P,先將其入棧。 * 如果P不存在左孩子和右孩子,則可以直接存取它;或者P存在左孩子或者右孩子,但是其左孩子和右孩子都已被訪問過了,則同樣可以直接存取該結點。 * 若非上述兩種情況,則將P的右孩子和左孩子依次入棧, * 這樣就保證了每次取棧頂元素的時候,左孩子在右孩子前面被訪問,左孩子和右孩子都在根結點前面被訪問。 */private Stack<TreeNode> stack = new Stack<TreeNode>();    public ArrayList<Integer> postorderTraversal(TreeNode root) {ArrayList<Integer> al = new ArrayList<Integer>();if (root != null) {TreeNode cur = null;TreeNode pre = null;    stack.push(root);    while (stack.size() != 0) {    cur = stack.peek();    if ((cur.left == null && cur.right == null) || (pre != null && (pre == cur.left || pre == cur.right))) {    al.add(cur.val);    pre = cur;    stack.pop();    } else {        if (cur.right != null) {        stack.push(cur.right);        }        if (cur.left != null) {        stack.push(cur.left);        }    }    }} return al;    }


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.