zoukankan      html  css  js  c++  java
  • 【leetcode】Convert Sorted Array to Binary Search Tree

    Convert Sorted Array to Binary Search Tree

    Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

     
    每次把中间元素当成根节点,递归即可
     
     1 /**
     2  * Definition for binary tree
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8  * };
     9  */
    10 class Solution {
    11 public:
    12     TreeNode *sortedArrayToBST(vector<int> &num) {
    13        
    14         TreeNode *root=buildTree(num,0,num.size()-1);
    15         return root;
    16     }
    17    
    18    
    19     TreeNode *buildTree(vector<int> &num,int l,int r)
    20     {
    21         if(l>r) return NULL;
    22        
    23         int mid=(l+r)/2;
    24        
    25         TreeNode *root=new TreeNode(num[mid]);
    26         root->left=buildTree(num,l,mid-1);
    27         root->right=buildTree(num,mid+1,r);
    28        
    29         return root;
    30     }
    31 };
  • 相关阅读:
    C# 设计模式-状态模式
    C# 设计模式-备忘录模式
    C# 设计模式-命令模式
    本地易优安装总结
    视频自动添加字幕
    百度商桥安装
    百度统计
    模板
    百度地图API
    栅格布局的理解
  • 原文地址:https://www.cnblogs.com/reachteam/p/4216234.html
Copyright © 2011-2022 走看看