589-N叉树的前序遍历
生活随笔
收集整理的這篇文章主要介紹了
589-N叉树的前序遍历
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
N階二叉樹:
class Tree {public int val;public List<Tree> children;public Tree() {}public Tree(int _val, List<Tree> _children) {val = _val;children = _children;}}迭代法遍歷:public List<Integer> preorder(Tree root) {List<Integer> list=new ArrayList<Integer>();if(root==null)return list;Stack<Tree> stack=new Stack<Tree>();stack.add(root);while (!stack.isEmpty()){Tree tree=stack.pop();list.add(tree.val);if (tree.children!=null){int n=tree.children.size();for (int i=n-1;i>=0;i--){stack.add(tree.children.get(i));}}}return list;}
}遞歸法遍歷:List<Integer> list = new ArrayList<>();public List<Integer> preorder(Tree root) {if (root == null) {return list;} else {list.add(root.val);for (int i = 0; i < root.children.size(); i++) {preorder(root.children.get(i));}return list;}}
}
?
轉載于:https://www.cnblogs.com/dloading/p/10908338.html
總結
以上是生活随笔為你收集整理的589-N叉树的前序遍历的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: springboot运行jar包时候加载
- 下一篇: spring boot的多环境部署