p43 将有序数组转化为二分搜索树 (leetcode 108)
Posted repinkply
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了p43 将有序数组转化为二分搜索树 (leetcode 108)相关的知识,希望对你有一定的参考价值。
一:解题思路
方法一:递归法 Time:O(n),Space:O(log(n))
方法二:迭代法 Time:O(n),Space:O(n)
二:完整代码示例 (C++版和Java版)
C++递归:
class Solution { public: TreeNode* sortedArrayToBST(vector<int>& nums,int start,int end) { if (start > end) return NULL; int mid = start + (end-start)/2; TreeNode* root = new TreeNode(nums[mid]); root->left = sortedArrayToBST(nums,start,mid-1); root->right = sortedArrayToBST(nums,mid+1,end); return root; } TreeNode* sortedArrayToBST(vector<int>& nums) { if (nums.size() == 0) return NULL; return sortedArrayToBST(nums,0,nums.size()-1); } };
Java递归:
class Solution { private TreeNode sortedArrayToBST(int[] nums,int start,int end) { if(start>end) return null; int mid=start+(end-start)/2; TreeNode root=new TreeNode(nums[mid]); root.left=sortedArrayToBST(nums,start,mid-1); root.right=sortedArrayToBST(nums,mid+1,end); return root; } public TreeNode sortedArrayToBST(int[] nums) { if(nums==null||nums.length==0) return null; return sortedArrayToBST(nums,0,nums.length-1); } }
C++迭代:
class Solution { public: struct Item { public: TreeNode* parent; int start; int end; bool isLeft; Item(TreeNode* parent, int start, int end, bool isLeft) { this->parent = parent; this->start = start; this->end = end; this->isLeft=isLeft; } }; TreeNode* sortedArrayToBST(vector<int>& nums) { if (nums.size() == 0) return NULL; stack<Item*> stack; TreeNode* dummy = new TreeNode(0); stack.push(new Item(dummy,0,nums.size()-1,true)); while (!stack.empty()) { Item* item = stack.top(); stack.pop(); if (item->start <= item->end) { int mid = item->start + (item->end-item->start) / 2; TreeNode* child = new TreeNode(nums[mid]); if (item->isLeft) item->parent->left = child; else item->parent->right = child; stack.push(new Item(child,item->start,mid-1,true)); stack.push(new Item(child,mid+1,item->end,false)); } } return dummy->left; } };
Java迭代:
class Solution { private class Item { TreeNode parent; int start; int end; boolean isLeft; Item(TreeNode parent,int start,int end,boolean isLeft) { this.parent=parent; this.start=start; this.end=end; this.isLeft=isLeft; } } public TreeNode sortedArrayToBST(int[] nums) { if(nums==null||nums.length==0) return null; TreeNode dummy=new TreeNode(0); Stack<Item> stack=new Stack<>(); stack.push(new Item(dummy,0,nums.length-1,true)); while(!stack.empty()) { Item item=stack.pop(); if(item.start<=item.end) { int mid=item.start+(item.end-item.start)/2; TreeNode child=new TreeNode(nums[mid]); if(item.isLeft) item.parent.left=child; else item.parent.right=child; stack.push(new Item(child,item.start,mid-1,true)); stack.push(new Item(child,mid+1,item.end,false)); } } return dummy.left; } }
以上是关于p43 将有序数组转化为二分搜索树 (leetcode 108)的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode 108. Convert Sorted Array to Binary Search Tree (有序数组转化为二叉搜索树)