LeetCode-N-ary Tree Preorder Traversal
阿新 • • 發佈:2018-12-13
Description: Given an n-ary tree, return the preorder traversal of its nodes’ values.
For example, given a 3-ary tree:
Return its preorder traversal as: [1,3,5,6,2,4].
Note: Recursive solution is trivial, could you do it iteratively?
題意:返回一顆N叉樹的前序遍歷節點值;
解法一(遞迴):將根節點的值插入到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 { List<Integer> result = new ArrayList<>(); public List<Integer> preorder(Node root) { if (root == null) return result; result.add(root.val); for (Node node : root.children) { preorder(node); } return result; } }
解法二(非遞迴):要想使用非遞迴實現前序遍歷,我們需要利用一個棧來儲存子節點;對每一個節點,我們從他的最後節點依次到最左節點存入到棧中;每一次,我們取出一個棧中元素,將其值插入到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> preorder(Node root) { List<Integer> result = new ArrayList<>(); Stack<Node> treeNode = new Stack<>(); if (root == null) return result; treeNode.push(root); while (!treeNode.isEmpty()) { Node temp = treeNode.pop(); result.add(temp.val); for (int i = temp.children.size() - 1; i >= 0; i--) { treeNode.push(temp.children.get(i)); } } return result; } }