LintCode 85. 在二叉查找树中插入节点
来源:互联网 发布:数据透视表 总计图标 编辑:程序博客网 时间:2024/06/15 17:37
题目: 在二叉查找树中插入节点
要求:
给定一棵二叉查找树和一个新的树节点,将节点插入到树中。
你需要保证该树仍然是一棵二叉查找树。
样例:
给出如下一棵二叉查找树,在插入节点6之后这棵二叉查找树可以是这样的:
给出如下一棵二叉查找树,在插入节点6之后这棵二叉查找树可以是这样的: 2 2 / \ / \1 4 --> 1 4 / / \ 3 3 6
算法要求:
能否不使用递归?
解题思路:
直接用栈来实现即可。
算法如下:
/** * Definition of TreeNode: * class TreeNode { * public: * int val; * TreeNode *left, *right; * TreeNode(int val) { * this->val = val; * this->left = this->right = NULL; * } * } */class Solution {public: /* * @param root: The root of the binary search tree. * @param node: insert this node into the binary search tree * @return: The root of the new binary search tree. */ TreeNode * insertNode(TreeNode * root, TreeNode * node) { // write your code here stack<TreeNode * > sta; sta.push(root); TreeNode * last = NULL; while (sta.size() != 0) { TreeNode * now = sta.top(); sta.pop(); if (now == NULL) { if (last == NULL) { root = node; } else if (last->val <= node->val) { last -> right = node; } else { last -> left = node; } break; } else if (now->val <= node->val) { sta.push(now->right); } else { sta.push(now->left); } last = now; } return root; }};
阅读全文
0 0
- LintCode 85. 在二叉查找树中插入节点
- lintcode-在二叉查找树中插入节点-85
- LintCode:在二叉查找树中插入节点
- lintcode ----在二叉查找树中插入节点
- LintCode(85)在二叉查找树中插入节点
- LintCode 85-在二叉查找树中插入节点
- 【lintcode笔记】在二叉查找树中插入节点
- lintcode——在二叉查找树中插入节点
- LintCode-在二叉查找树中插入节点
- lintcode 在二叉查找树中插入节点
- LintCode 在二叉查找树中插入节点
- 在二叉查找树中插入节点-LintCode
- LintCode 在二叉查找树中插入节点
- 在二叉查找树中插入节点-LintCode
- LintCode Insert a Node in a Binary Search Tree 在二叉查找树中插入节点
- lintcode insert-node-in-a-binary-search-tree 在二叉查找树中插入节点
- LintCode(S)二叉查找树插入节点
- 在二叉查找树中插入节点
- Python入门(八)
- MapReduce之WordCount单词计数
- 利用MapReduce进行排序
- 二叉树各种基本运算的算法
- Struts访问Servlet API
- LintCode 85. 在二叉查找树中插入节点
- Action搜索顺序-Struts2深入
- Struts2的工作原理及文件结构
- Hive基本概念
- MapReduce之WordCount单词计数(下)
- 动态方法调用-深入Struts2
- 手机解锁
- 指定多个配置文件-深入Struts2
- 默认Action-深入Struts2