美文网首页
leetcode--589--N叉树的前序遍历

leetcode--589--N叉树的前序遍历

作者: minningl | 来源:发表于2020-11-14 01:05 被阅读0次

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

    例如,给定一个 3叉树 :

    image

    返回其前序遍历: [1,3,5,6,2,4]

    思路:
    1、前序遍历:按照【根左右】的顺序遍历root节点

    Python代码:

    """
    # Definition for a Node.
    class Node(object):
        def __init__(self, val=None, children=None):
            self.val = val
            self.children = children
    """
    
    class Solution(object):
    
        def __init__(self):
            self.ret = []
    
        def preorder(self, root):
            """
            :type root: Node
            :rtype: List[int]
            """
            ret = []
            if not root:
                return None
            self.ret.append(root.val)
            for item in root.children:
                self.preorder(item)
            return self.ret
    

    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:
    
        vector<int> ret;
    
        vector<int> preorder(Node* root) {
            if (root==nullptr) {
                return ret;
            }
            ret.push_back(root->val);
            for (auto item : root->children){
                preorder(item);
            }
            
            return ret;
        }
    };
    

    思路2:
    1、非递归版:定义一个队列,存放进去root。递归的pop出队列的首位元素,并按照从右往左的顺序依次将首位元素的子节点加入到队列中

    Python代码:

    """
    # Definition for a Node.
    class Node(object):
        def __init__(self, val=None, children=None):
            self.val = val
            self.children = children
    """
    
    class Solution(object):
    
        def __init__(self):
            self.ret = []
    
        def preorder(self, root):
            """
            :type root: Node
            :rtype: List[int]
            """
            if not root:
                return None
            deque = [root]
            ret = []
    
            while deque:
                item = deque.pop()
                ret.append(item.val)
                for i in range(len(item.children)-1,-1,-1):
                    deque.append(item.children[i])
            return ret
    

    相关文章

      网友评论

          本文标题:leetcode--589--N叉树的前序遍历

          本文链接:https://www.haomeiwen.com/subject/qtdibktx.html