Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

N叉树的层序遍历 #28

Open
HealUP opened this issue May 18, 2023 · 0 comments
Open

N叉树的层序遍历 #28

HealUP opened this issue May 18, 2023 · 0 comments
Labels
算法 记录刷题记录,代码随想录

Comments

@HealUP
Copy link
Owner

HealUP commented May 18, 2023

N叉树的层序遍历

思路:依然是层序遍历,只是节点的孩子有多个了,children也是List类型的,将节点的所有孩子遍历后全部放入队列即可:

遍历方式

  • 增强for循环
  • 普通for循环
class Solution {
    public List<List<Integer>> levelOrder(Node root) {
        List<List<Integer>> result = new ArrayList<>();
        Queue<Node> que = new LinkedList<>();
        if (root != null) {
            que.offer(root);
        }
        while (!que.isEmpty()) {
            List<Integer> list = new ArrayList<>();
            int len = que.size();
            for (int i = 0; i < len; i++) {
                Node node = que.poll();
                list.add(node.val);//取出节点的值加入到结果集
                //添加节点的孩子到队列,是Node类型的List
                List<Node> children = node.children;
                //遍历孩子,放到队列中
                // for (int j = 0; j < children.size(); j++) {
                //     if (children.get(j) != null ) {
                //         que.offer(children.get(j));//将节点加入到队列
                //     }
                // }
                for (Node child : children) {
                    if (child != null) {
                        que.offer(child);
                    }
                }
            }
            result.add(list);
        }
        return result;
    }
}

N叉树(节点)的定义

// Definition for a Node.
class Node {
    public int val;
    public List<Node> children;//孩子也是节点类型的

    public Node() {}//构造器

    public Node(int _val) {//有参构造器
        val = _val;
    }

    public Node(int _val, List<Node> _children) {//有参构造器
        val = _val;
        children = _children;
    }
};
@HealUP HealUP added 算法 记录刷题记录,代码随想录 二叉树 labels May 18, 2023
@HealUP HealUP removed the 二叉树 label Jul 29, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
算法 记录刷题记录,代码随想录
Projects
None yet
Development

No branches or pull requests

1 participant