Leetcode-Binary Tree Postorder Traversal

來源:互聯網
上載者:User

標籤:des   style   blog   io   ar   color   os   sp   for   

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?

Solution:

 1 /** 2  * Definition for binary tree 3  * public class TreeNode { 4  *     int val; 5  *     TreeNode left; 6  *     TreeNode right; 7  *     TreeNode(int x) { val = x; } 8  * } 9  */10 public class Solution {11     public List<Integer> postorderTraversal(TreeNode root) {12         List<Integer> res = new ArrayList<Integer>();13         if (root==null) return res;14 15         Stack<TreeNode> nStack = new Stack<TreeNode>();16         Stack<Integer> record = new Stack<Integer>();17         nStack.push(root);18         record.push(0);19 20         while (nStack.size()!=0){21             TreeNode cur = nStack.peek();22             if (cur.left==null && cur.right==null){23                 res.add(cur.val);24                 nStack.pop();25                 record.pop();26                 continue;27             }28 29             int val = record.peek();30             if (val==0){31                 record.pop();32                 record.push(val+1);33                 if (cur.left!=null){34                     nStack.push(cur.left);35                     record.push(0);36                 }37                 continue;38             }39 40             if (val==1){41                 record.pop();42                 record.push(val+1);43                 if (cur.right!=null){44                     nStack.push(cur.right);45                     record.push(0);46                 }47                 continue;48             }49 50             if (val==2){51                 res.add(cur.val);52                 nStack.pop();53                 record.pop();54                 continue;55             }56         }57 58         return res;  59         60     }61 }

 

Leetcode-Binary Tree Postorder Traversal

聯繫我們

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