My Thirty-fifth Page - 最大二叉树 - By Nicolas
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                My Thirty-fifth Page - 最大二叉树 - By Nicolas
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.                        
                                這篇page是針對leetcode上的654.最大二叉樹所寫的。小尼先簡單的說明一下這道題的意思給定一個不重復的數組nums,創造一個根節點,nums中的最大值為根節點,遞歸最大值左邊創建左子樹,遞歸右邊創建右子樹。小尼這邊給出遞歸的寫法:
class Solution {public TreeNode constructMaximumBinaryTree(int[] nums) {return constructMaximumBinaryTree1(nums,0,nums.length);}public TreeNode constructMaximumBinaryTree1(int[] nums,int leftindex, int rightindex){if(rightindex - leftindex < 1){return null;}if(rightindex - leftindex == 1){return new TreeNode(nums[leftindex]);}int maxIndex = leftindex;int maxVal = nums[maxIndex];for(int i = leftindex + 1;i<rightindex;i++){if(nums[i]>maxVal){maxVal = nums[i];maxIndex = i;}}TreeNode root = new TreeNode(maxVal);root.left = constructMaximumBinaryTree1(nums,leftindex,maxIndex);root.right = constructMaximumBinaryTree1(nums,maxIndex + 1,rightindex);return root;} }供小伙伴參考
總結
以上是生活随笔為你收集整理的My Thirty-fifth Page - 最大二叉树 - By Nicolas的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: 如何查计算机硬盘型号,如何查看硬盘的型号
- 下一篇: 利用传输矩阵法求解布拉格光栅的透射谱
