1、二叉树框架
void traverse(TreeNode root) {
【
】
traverse(root.left);
traverse(root.right);
}
<1>把二叉树所有的节点中的值加一
void plusOne(TreeNode root) {
if (root == null) return;
root.val += 1;
plusOne(root.left);
plusOne(root.right);
}
<2> 如何判断两棵二叉树是否完全相同
boolean isSameTree(TreeNode root1, TreeNode root2) {
if (root1 == null && root2 == null) return true;
if (root1 == null || root2 == null) return false;
if (root1.val != root2.val) return false;
return isSameTree(root1.left, root2.left)
&& isSameTree(root1.right, root2.right);
}
2、BST框架
void BST(TreeNode root, int target) {
if (root.val == target)
【
if (root.val < target)
BST(root.right, target);
if (root.val > target)
BST(root.left, target);
}
(1)BST的搜索
TreeNode* searchBST(TreeNode* root, int val) {
if(nullptr == root) return NULL;
if(root->val == val) return root;
return root->val > val?searchBST(root->left,val):searchBST(root->right,val);
}
(2)BST插入
TreeNode* insertIntoBST(TreeNode* root, int val) {
if(nullptr == root) return new TreeNode(val);
if(root->val > val){
root->left = insertIntoBST(root->left,val);
}else{
root->right = insertIntoBST(root->right,val);
}
return root;
}
(3)BST删除
TreeNode* deleteNode(TreeNode* root, int key) {
if(root == nullptr) return root;
if(root->val < key) root->right = deleteNode(root->right,key);
else if(root->val > key) root->left = deleteNode(root->left,key);
else{
if(nullptr == root->left && nullptr == root->right){
return nullptr;
}
if(nullptr == root->left && nullptr != root->right){
return root->right;
}
if(nullptr == root->right && nullptr != root->left){
return root->left;
}
if(nullptr != root->left && nullptr != root->right){
TreeNode* node = root->right;
while(nullptr != node->left){
node = node->left;
}
node->left = root->left;
root = root->right;
}
}
return root;
}