怎样做网站xml,潍坊企业网络推广,1cpu0.5g服务器用来做网站,区域代理加盟项目题目
589. N 叉树的前序遍历
分析
我们之前有做过LeetCode的 144. 二叉树的前序遍历#xff0c;其实对于 N 插树来说和二叉树的思路是一模一样的。 二叉树的前序遍历是【根 左 右】 N叉树的前序遍历顺序是【根 孩子】#xff0c;你可以把二叉树的【根 左 右】想象成【根 孩…题目
589. N 叉树的前序遍历
分析
我们之前有做过LeetCode的 144. 二叉树的前序遍历其实对于 N 插树来说和二叉树的思路是一模一样的。 二叉树的前序遍历是【根 左 右】 N叉树的前序遍历顺序是【根 孩子】你可以把二叉树的【根 左 右】想象成【根 孩子】因为左右就是孩子。
代码
先看一下二叉树前序遍历的代码
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode() {}* TreeNode(int val) { this.val val; }* TreeNode(int val, TreeNode left, TreeNode right) {* this.val val;* this.left left;* this.right right;* }* }*/
class Solution {public ListInteger preorderTraversal(TreeNode root) {ListInteger res new ArrayList();func(root,res);return res;}void func(TreeNode cur,ListInteger res) {if(cur null) return;// 先记录根节点res.add(cur.val);// 遍历左子树func(cur.left,res);// 遍历右子树func(cur.right,res);}
}
只需要改动一点就是N叉树的前序遍历代码如下
/*
// Definition for a Node.
class Node {public int val;public ListNode children;public Node() {}public Node(int _val) {val _val;}public Node(int _val, ListNode _children) {val _val;children _children;}
};
*/class Solution {public ListInteger preorder(Node root) {ListInteger res new ArrayList();if(root null) return res;pre(root,res);return res;}void pre(Node cur,ListInteger res) {if(cur null) return ;// 先记录当前节点res.add(cur.val);// 再遍历孩子for(Node node : cur.children) {pre(node,res);}}
}