在二叉树的问题基础上,扩展到了N叉树,但是方法运用类似
需要解决N叉树的遍历问题,常见的有前序遍历和后序遍历,还有N叉树的最大深度问题
给定一个 n 叉树的根节点 root
,返回 其节点值的 前序遍历 ,后序遍历
前序遍历:递归
/**
* Definition for a Node.
* struct Node {
* int val;
* int numChildren;
* struct Node** children;
* };
*/
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
#define MAX_NODE_SIZE 10000
void helper(const struct Node*root,int *res,int *pos)
{
if(root==NULL)
return;
res[(*pos)++]=root->val;
for(int i=0;i<root->numChildren;i++)
{
helper(root->children[i],res,pos);
}
}
int* preorder(struct Node* root, int* returnSize) {
int* res=(int*)malloc(sizeof(int)*MAX_NODE_SIZE);
int pos=0;
helper(root,res,&pos);
*returnSize=pos;
return res;
}
后序遍历:递归
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
void postorder(struct TreeNode* root, int* res, int* resSize)
{
if (root == NULL)
return;
postorder(root->left, res, resSize);
postorder(root->right, res, resSize);
res[(*resSize)++] = root->val;
}
int* postorderTraversal(struct TreeNode* root, int* returnSize) {
int* res = malloc(sizeof(int) * 2000);
*returnSize = 0;
postorder(root, res, returnSize);
return res;
}
给定一个 N 叉树,找到其最大深度。
最大深度是指从根节点到最远叶子节点的最长路径上的节点总数。
解:与二叉树一样,采用深度优先搜索和递归解决
/**
* Definition for a Node.
* struct Node {
* int val;
* int numChildren;
* struct Node** children;
* };
*/
int maxDepth(struct Node* root) {
if(root==NULL)
return 0;
int maxChildDepth=0;
for(int i=0;i<root->numChildren;i++)
{
maxChildDepth=fmax(maxChildDepth,maxDepth(root->children[i]));
}
return maxChildDepth+1;
}
在此提供python的写法
class Node:
def __init__(self, val=None, children=None):
self.val = val
self.children = children
"""
class Solution:
def maxDepth(self, root: 'Node') -> int:
if root==None:
return 0
else:
return max((self.maxDepth(child) for child in root.children),default=0)+1