4.6 Write an algorithm to find the'next'node (i.e., in-order successor) of a given node in a binary search tree. You may assume that each node has a link to its parent. 这道题实际上考察的是一种叫线索二叉树的数据结构,而构造这种树的方法称之为Morris遍历法,在我之前的博客Binary Tree Inorder Traversa…
Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return the root node reference (possibly updated) of the BST. Basically, the deletion can be divided into two stages: Search for a node to remove. If the n…
Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return the root node reference (possibly updated) of the BST. Basically, the deletion can be divided into two stages: Search for a node to remove. If the n…
详见:https://leetcode.com/problems/delete-node-in-a-bst/description/ C++: /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class…
Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return the root node reference (possibly updated) of the BST. Basically, the deletion can be divided into two stages: Search for a node to remove. If the n…
4.3 Given a sorted (increasing order) array with unique integer elements, write an algorithm to create a binary search tree with minimal height. 这道题给了我们一个有序的数组,让我们来生成一个最小高度的二叉搜索树,为了达到最小高度,肯定是尽可能的填成一个满二叉树,左子树填满,右子树尽可能的填满.而且要注意是二叉搜索树,左<根<右的性质不能忘.既然给了我…
4.5 Implement a function to check if a binary tree is a binary search tree. LeetCode上的原题,请参见我之前的博客Validate Binary Search Tree 验证二叉搜索树.…
二叉树变量只是一个地址 public static void main(String[] args) { TreeNode t = new TreeNode(3); help(t); System.out.println(t.val); } public static void help(TreeNode t) { t.val = 6; } 上边代码通过地址改变了二叉树,输出为6,但是下边代码却只是传入函数的二叉树变量指向了另一个地址,外界的二叉树变量和二叉树的值没有变,输出还是3 public…
Find the second largest node in the BST 分析: 如果root有右节点,很明显第二大的node有可能在右子树里.唯一不满足的条件就是右子树只有一个node. 这个时候root就是第二大node. 所以我们需要把root(可能是第二大node)也传下去. 如果root没有右节点,我们只要找左子树的最大node就可以了. public class Solution { public Node secondLargest(Node root) { return h…
问题 给出如下结构的二叉树: struct TreeLinkNode { TreeLinkNode *left; TreeLinkNode *right; TreeLinkNode *next; } 填充每一个next指针使其指向自己的右边邻居节点.如果没有右边的邻居节点,next指针须设成NULL. 在开始时,所有的next指针被初始化成NULL. 注意: 你只能使用常数级别的额外空间 你可以假设该树为完全二叉树(即所有叶子节点都在同一层,而且每个父节点都有两个子节点). 例如,给出如下完全二…