1.题目描述 2.分析 插入算法. 3.代码 TreeNode* insertIntoBST(TreeNode* root, int val) { insert(root, val); return root; } void insert(TreeNode * & t , int val) { if (t == NULL) t = new TreeNode(val); else if (val < t->val) { insert(t->left, val); } else if…
1.题目描述 2.问题分析 使用map记录元素出现的次数. 3.代码 vector<int> v; map<int,int> m; vector<int> findMode(TreeNode* root) { if (root == NULL) return v; preOrder(root); ; for(map<int,int>::iterator it = m.begin(); it != m.end(); it++) { if (it->sec…
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST. 题意:给定一个有序的链表,将其转换成平衡二叉搜索树 思路: 二分法 要构建一个平衡二叉树,二分法无疑是合适的,至于如何分是的代码简洁,就需要用到递归了. class Solution { public: // find middle element of the list Lis…
Given an array where elements are sorted in ascending order, convert it to a height balanced BST. For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more th…
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST. For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never diffe…
Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST. According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has…
https://leetcode.com/submissions/detail/32662938/ Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST. According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between t…
Given an array where elements are sorted in ascending order, convert it to a height balanced BST. 题目标签:Tree 这道题目给了我们一个有序数组,从小到大.让我们把这个数组转化为height balanced BST. 首先来看一下什么是binary search tree: 每一个点的left < 节点 < right, 换一句话说,每一个点的值要大于左边的,小于右边的. 那么什么是heigh…
Given a binary tree, determine if it is a valid binary search tree (BST). Assume a BST is defined as follows: The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node contains only nodes with keys…
Two elements of a binary search tree (BST) are swapped by mistake. Recover the tree without changing its structure. Note:A solution using O(n) space is pretty straight forward. Could you devise a constant space solution? 题解:需要找到二叉搜索树中乱序的两个节点,并把它们交换回来…