Java中二叉树与N叉树的示例分析(java,开发技术)

时间:2024-05-04 00:05:57 作者 : 石家庄SEO 分类 : 开发技术
  • TAG :

题目一

Java中二叉树与N叉树的示例分析

解法

/***Definitionforabinarytreenode.*publicclassTreeNode{*intval;*TreeNodeleft;*TreeNoderight;*TreeNode(){}*TreeNode(intval){this.val=val;}*TreeNode(intval,TreeNodeleft,TreeNoderight){*this.val=val;*this.left=left;*this.right=right;*}*}*/classSolution{StringBuffersb=newStringBuffer();List<String>list=newArrayList<String>();publicList<String>binaryTreePaths(TreeNoderoot){method(root);returnlist;}publicvoidmethod(TreeNoderoot){if(root==null)return;intt=sb.length();sb.append(root.val);if(root.left==null&&root.right==null){list.add(sb.toString());}sb.append("->");method(root.left);method(root.right);sb.delete(t,sb.length());}}

题目二

Java中二叉树与N叉树的示例分析

解法

/***Definitionforabinarytreenode.*publicclassTreeNode{*intval;*TreeNodeleft;*TreeNoderight;*TreeNode(){}*TreeNode(intval){this.val=val;}*TreeNode(intval,TreeNodeleft,TreeNoderight){*this.val=val;*this.left=left;*this.right=right;*}*}*/classSolution{intans=0;publicintsumOfLeftLeaves(TreeNoderoot){method(root,false);returnans;}publicvoidmethod(TreeNoderoot,booleanflag){if(root==null)return;if(root.left==null&&root.right==null&&flag){ans+=root.val;return;}method(root.left,true);method(root.right,false);}}

题目三

Java中二叉树与N叉树的示例分析

解法

/*//DefinitionforaNode.classNode{publicintval;publicList<Node>children;publicNode(){}publicNode(int_val){val=_val;}publicNode(int_val,List<Node>_children){val=_val;children=_children;}};*/classSolution{publicintmaxDepth(Noderoot){if(root==null){return0;}intmaxChildDepth=0;for(inti=0;i<root.children.size();i++){intchildDepth=maxDepth(root.children.get(i));maxChildDepth=Math.max(maxChildDepth,childDepth);}returnmaxChildDepth+1;}}
 </div> <div class="zixun-tj-product adv-bottom"></div> </div> </div> <div class="prve-next-news">
本文:Java中二叉树与N叉树的示例分析的详细内容,希望对您有所帮助,信息来源于网络。
上一篇:如何使用vue监听页面中某个div的滚动事件并判断滚动位置下一篇:

4 人围观 / 0 条评论 ↓快速评论↓

(必须)

(必须,保密)

阿狸1 阿狸2 阿狸3 阿狸4 阿狸5 阿狸6 阿狸7 阿狸8 阿狸9 阿狸10 阿狸11 阿狸12 阿狸13 阿狸14 阿狸15 阿狸16 阿狸17 阿狸18