lintcode 1526. N叉树的前序遍历

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

样例
样例

输入 : {1,3,2,4#2#3,5,6#4#5#6}
输出: [1,3,5,6,2,4]
/**
 * Definition for undirected graph.
 * struct UndirectedGraphNode {
 *     int label;
 *     vector<UndirectedGraphNode *> neighbors;
 *     UndirectedGraphNode(int x) : label(x) {};
 * };
 */

class Solution {
public:
    /**
     * @param root: the tree
     * @return: pre order of the tree
     */
    vector<int> preorder(UndirectedGraphNode* root) {
        // write your code here
        vector<int> res;
        recursion(root,res);
        return res;
    }
    void recursion(UndirectedGraphNode* root,vector<int> &res)
    { 
        if(root==NULL) return; 
        res.push_back(root->label);
        for (int i = 0; i < root->neighbors.size(); i++) {
            /* code */
            recursion(root->neighbors[i],res);
        }
    }
};
发布了335 篇原创文章 · 获赞 13 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_43981315/article/details/103951070