Java中二叉树与N叉树的示例分析
这篇文章主要介绍了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());}}
题目二

解法
/***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);}}
题目三

解法
/*//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;}}
感谢你能够认真阅读完这篇文章,希望小编分享的“Java中二叉树与N叉树的示例分析”这篇文章对大家有帮助,同时也希望大家多多支持恰卡编程网,关注恰卡编程网行业资讯频道,更多相关知识等着你来学习!