二叉排序树删除节点
来源:互联网 发布:淘宝优秀的试用报告 编辑:程序博客网 时间:2024/06/11 12:00
#include<iostream>using namespace std;class TreeNode {public: int val; TreeNode *left, *right; TreeNode(int val) { this->val = val; this->left = this->right = NULL; }};class Solution {public: TreeNode* removeNode(TreeNode* root, int val) { // if root is null, just return if (!root) return root; // Find node whose val equal to "val" TreeNode* parent = NULL; TreeNode* curr = root; while (curr) { if (curr->val == val) break; parent = curr; if (curr->val > val) curr = curr->left; else curr = curr->right; } // If there is no node's value equals to val if (!curr) return root; // Situation 1, leafe node if (!curr->left && !curr->right) { if (!parent) { root = NULL; } else { if (parent->left == curr) parent->left = NULL; else parent->right = NULL; } delete curr; } else if (curr->left && !curr->right) { // Situation 2, no right child if (!parent) { root = curr->left; } else { if (parent->left == curr) parent->left = curr->left; else parent->right = curr->left; } delete curr; } else if (!curr->left && curr->right) { // Situation 3, no left child if (!parent) { root = curr->right; } else { if (parent->left == curr) parent->left = curr->right; else parent->right = curr->right; } delete curr; } else { // Situation 4, both childs are existing TreeNode* left_max = curr->left; parent = curr; while (left_max->right) { parent = left_max; left_max = left_max->right; } // Swap with curr node curr->val = curr->val ^ left_max->val; left_max->val = curr->val ^ left_max->val; curr->val = curr->val ^ left_max->val; // Delete left_max if (parent->left == left_max) parent->left = NULL; else if (parent->right == left_max) parent->right = NULL; delete left_max; } return root; }};void pLevel(TreeNode* node) { if (!node) return; cout << node->val << endl; pLevel(node->left); pLevel(node->right);}int main() { TreeNode* node5 = new TreeNode(5); TreeNode* node3 = new TreeNode(3); TreeNode* node6 = new TreeNode(6); TreeNode* node2 = new TreeNode(2); TreeNode* node4 = new TreeNode(4); node5->left = node3; node5->right = node6; node3->left = node2; node3->right = node4; Solution s; TreeNode* ret = s.removeNode(node5, 3); pLevel(ret); return 0;}
0 0
- 二叉排序树之删除节点
- 二叉排序树删除节点
- 二叉排序树删除节点
- 二叉排序树中删除一个节点
- 删除二叉排序树中的一个节点
- 二叉排序树节点删除(c++)
- 二叉排序树删除节点的几种方法
- 二叉排序树节点删除&简单性能分析
- 在一颗二叉排序树上删除节点
- C++建立查找删除节点二叉排序树
- java实现二叉排序树的删除节点
- 二叉排序树,完成创建节点,插入节点,删除节点,查找节点,中序遍历的功能
- 二叉排序树的创建和遍历与删除指定的节点
- 二叉排序树(二叉查找树)BST构造,节点插入,节点查找,节点删除(java)
- 二叉排序树数值最接近节点
- 二叉排序树的建立和树中节点的查找删除操作
- 算法:二叉排序树的删除节点策略及其图形化(二叉树查找)
- 关于java写二叉排序树的问题,实现各种节点的插入,删除,遍历
- hdoj 1237 简单计算器
- Linux wait()函数 http://blog.163.com/lqy_super/blog/static/1997510212012112953858902/
- 对Hash Join的一次优化之--10104 trace-bucket
- 苹果操作系统(OS X和iOS)表情字符
- MongoDB学习日记(九):index
- 二叉排序树删除节点
- Java 对jni的调用
- 兔子--查看Android Studio的版本信息
- CSS 相对/绝对(relative/absolute)定位系列(四)
- AngularJS——1
- CSDN博客积分规则和获取积分方法
- OC之内存管理(个人笔记)
- CSS 相对|绝对(relative/absolute)定位系列(一)
- #leetcode#First Bad Version