LeetCode(109) Convert Sorted List to Binary Search Tree
来源:互联网 发布:杭州市物联网产业数据 编辑:程序博客网 时间:2024/05/22 04:51
题目
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
分析
给定有序链表,构造平衡的二叉查找树。
与上题本质相同,只不过采用了不同的数据结构,本题关键在于准确求取链表节点数,并计算根节点所在位置,正确划分左右子树的子链表。
注意:指针处理,避免出现空指针引用。
AC代码
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; *//** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: TreeNode* sortedListToBST(ListNode* head) { if (head == NULL) return NULL; int size = 0; ListNode *p = head; while (p) { ++size; p = p->next; } ListNode *l = head, *r = NULL; //查找中间节点,用于构造二叉树根节点 ListNode *pre = head; p = head; int i = 0; while (p && i < size / 2) { pre = p; p = p->next; ++i; } //p节点作为根节点 TreeNode *root = new TreeNode(p->val); // 其余节点为右子树 r = p->next; //之前节点为左子树 if (pre->next == p) pre->next = NULL; else l = NULL; root->left = sortedListToBST(l); root->right = sortedListToBST(r); return root; }};
GitHub测试程序源码
0 0
- LeetCode(109) Convert Sorted List to Binary Search Tree
- LeetCode(109)Convert Sorted List to Binary Search Tree
- LeetCode: Convert Sorted List to Binary Search Tree [109]
- LeetCode 109 Convert Sorted List to Binary Search Tree
- LeetCode 109 Convert Sorted List to Binary Search Tree
- [leetcode 109] Convert Sorted List to Binary Search Tree
- [LeetCode 109]Convert Sorted List to Binary Search Tree
- leetcode || 109、Convert Sorted List to Binary Search Tree
- 【leetcode】【单链表】【109】Convert Sorted List to Binary Search Tree
- Convert Sorted List to Binary Search Tree - LeetCode 109
- leetcode[109]:Convert Sorted List to Binary Search Tree
- LeetCode(109) Convert Sorted List to Binary Search Tree
- Leetcode #109 Convert Sorted List to Binary Search Tree
- leetcode 109: Convert Sorted List to Binary Search Tree
- 109 Convert Sorted List to Binary Search Tree [Leetcode]
- LeetCode—109 Convert Sorted List to Binary Search Tree
- 【LEETCODE】109-Convert Sorted List to Binary Search Tree
- LeetCode 109 Convert Sorted List to Binary Search Tree
- 关于smtp和pop3的端口
- android VelocityTracker的简单用法
- Graph Visualization and Navigation in Information Visualization: A Survey 译文
- 地图 svg中国地图、echarts百度迁徙图
- UFT 常见运行出错问题分析
- LeetCode(109) Convert Sorted List to Binary Search Tree
- 频谱播放器
- jQuery实现打印输出字体
- 我的CSDN博客三周年------不是坚持, 而是热爱!
- intellij idea之servlet
- 如何完全卸载SQL SERVER?
- hdu5504
- 《剑指Offer》面试题:重构二叉树
- 黑马程序员——GUI