4-2 LC589 N叉树的前序遍历 C++ JAVA python力扣刷题笔记

LC589 N叉树的前序遍历

在这里插入图片描述
LC589

1.读题

给定一个 N 叉树,返回其节点值的 前序遍历 。

N 叉树 在输入中按层序遍历进行序列化表示,每组子节点由空值 null 分隔(请参见示例)。

提示:

  • N 叉树的高度小于或等于 1000
  • 节点总数在范围 [0, 10^4] 内

实例1
在这里插入图片描述
输入:root = [1,null,3,2,4,null,5,6]
输出:[1,3,5,6,2,4]

实例2
在这里插入图片描述
输入:root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
输出:[1,2,3,6,7,11,14,4,8,12,5,9,13,10]

2.思路

就递归就完事了~
简单难度的题嘛 相比于 LC144 不需要考虑左子树和右子树的遍历
只需要

在遍历到的节点仍是节点的子节点时 递归就完事了!
即为使用——
for(auto x : root->children)做判断

(这个语句的意思是迭代容器中所有的元素 每个元素的临时名字为x)

3. C++代码实现

递归方法:

/*
// Definition for a Node.
class Node {
public:
    int val;
    vector<Node*> children;

    Node() {}

    Node(int _val) {
        val = _val;
    }

    Node(int _val, vector<Node*> _children) {
        val = _val;
        children = _children;
    }
};
*/

class Solution {
public:
    void __preorder(Node *root,vector<int> &res) {
        if (root == NULL) return; //退出条件

        res.push_back(root->val); //节点值入队列
        for(auto x : root->children) 
        //迭代容器中所有的元素 每个元素的临时名字为x
            __preorder(x,res); //递归遍历
        }
    }
    vector<int> preorder(Node* root) {
        vector<int> res;
        __preorder(root,res);
        return res;
    }
};

在这里插入图片描述

4.python代码实现

"""
# Definition for a Node.
class Node:
    def __init__(self, val=None, children=None):
        self.val = val
        self.children = children
"""

class Solution:
    def preorder(self, root:'Node') -> List[int]:
        result = [] #结果数组
        #前序遍历
        def pre_order(root):
            if root:
                result.append(root.val)
                for node in root.children:
                    pre_order(node)
        
        pre_order(root)
        return result

		

python写起来就简单得多辽!
在这里插入图片描述

5.JAVA代码

class Solution {
    public List<Integer> preorder(Node root) {
        LinkedList<Node> stack = new LinkedList<>();
        LinkedList<Integer> output = new LinkedList<>();

        if (root == null) {
            return output;
        }

        stack.add(root);
        while (!stack.isEmpty()) {
            Node node = stack.pollLast();
            output.add(node.val);
            Collections.reverse(node.children);
            for (Node item:node.children) {//遍历完所有子节点为止
                stack.add(item);
            }
        }
        return output;
    }
}

再放一个简单点的方法~

class Solution {
    List<Integer> res = new ArrayList<Integer>();
    public List<Integer> preorder(Node root) {
        if (root == null){
            return res;
        }   
        res.add(root.val);//节点值挨个入队列~
        // 遍历N叉树的所有节点!每个节点的临时名字为child
        for (Node child:root.children){
            preorder(child);
        }
        return res;
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值