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;
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/dloading/p/10908338.html