LeetCode-N-ary Tree Postorder Traversal
阿新 • • 發佈:2018-12-13
Description: Given an n-ary tree, return the postorder traversal of its nodes’ values.
For example, given a 3-ary tree:
Return its postorder traversal as: [5,6,3,2,4,1].
Note: Recursive solution is trivial, could you do it iteratively?
題意:給定一顆N叉樹,要求返回後序遍歷的節點值;
解法一(遞迴):我們可以很容易的想到用遞迴來解決樹的遍歷問題;對於每一個節點,我們依次訪問他們的每一個子節點,對於每一個子節點,再遞迴的遍歷自己的子節點;
Java
/* // Definition for a Node. class Node { public int val; public List<Node> children; public Node() {} public Node(int _val,List<Node> _children) { val = _val; children = _children; } }; */ class Solution { public List<Integer> postorder(Node root) { LinkedList<Integer> result = new LinkedList<>(); if (root == null) return result; for (int i = 0; i < root.children.size(); i++) { postorder(root.children.get(i), result); } result.addLast(root.val); return result; } private void postorder(Node root, LinkedList<Integer> result) { if (root.children.size() == 0) { result.addLast(root.val); return; } for (int i = 0; i < root.children.size(); i++) { postorder(root.children.get(i), result); } result.add(root.val); } }
解法二(非遞迴):如果要利用非遞迴來解決這個問題的話,我們需要藉助一個棧來儲存子節點,對於每一個節點,我們將其所有的子節點都入棧;每一次,我們都從棧中取出一個節點,將其插入到list的首部(因為棧是後進先出的,所有第一個子節點是先入棧最後出棧的);
Java
/* // Definition for a Node. class Node { public int val; public List<Node> children; public Node() {} public Node(int _val,List<Node> _children) { val = _val; children = _children; } }; */ class Solution { public List<Integer> postorder(Node root) { LinkedList<Integer> result = new LinkedList<>(); Stack<Node> treeNode = new Stack<>(); if (root == null) return result; treeNode.push(root); while (!treeNode.isEmpty()) { Node temp = treeNode.pop(); result.addFirst(temp.val); for (Node node : temp.children) { treeNode.push(node); } } return result; } }