#85 Insert Node in a Binary Search Tree
来源:互联网 发布:洛天依软件手机版 编辑:程序博客网 时间:2024/05/29 17:39
题目描述:
Given a binary search tree and a new tree node, insert the node into the tree. You should keep the tree still be a valid binary search tree.
Notice
You can assume there is no duplicate values in this tree + node.
Example
Given binary search tree as follow, after Insert node 6, the tree should be:
2 2 / \ / \1 4 --> 1 4 / / \ 3 3 6
Challenge
题目思路:Can you do it without recursion?
这题不用recursion做的话,就还是用BFS的思路。因为是BST,所以可以有方向的往下(要么左子树,要么右子树)。当遇到null的时候,就把新node连上去。
Mycode(AC = 42ms):
/** * 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 if (root == NULL) return node; queue<TreeNode *> helper; helper.push(root); while (!helper.empty()) { TreeNode *tmp = helper.front(); helper.pop(); if (node->val > tmp->val) { if (tmp->right) { helper.push(tmp->right); } else { tmp->right = node; } } else { if (tmp->left) { helper.push(tmp->left); } else { tmp->left = node; } } } return root; }};
0 0
- Insert Node in a Binary Search Tree
- Insert Node in a Binary Search Tree
- #85 Insert Node in a Binary Search Tree
- [刷题]Insert Node in a Binary Search Tree
- lintcode: Insert Node in a Binary Search Tree
- Lintcode85 Insert Node In A Binary Search Tree solution 题解
- LintCode Insert a Node in a Binary Search Tree 在二叉查找树中插入节点
- lintcode insert-node-in-a-binary-search-tree 在二叉查找树中插入节点
- 85.Insert Node in a Binary Search Tree-在二叉查找树中插入节点(容易题)
- Remove Node in Binary Search Tree
- Lintcode - Remove Node in Binary Search Tree
- [刷题]Remove Node in Binary Search Tree
- lintcode:Remove Node in Binary Search Tree
- Remove Node in Binary Search Tree
- Random Node in A Binary Tree
- 04-树4. Search in a Binary Search Tree (25)
- 04-树4. Search in a Binary Search Tree
- 04-树7. Search in a Binary Search Tree (25)
- PHP WebShell源码下载(1)
- C语言 FILE结构体
- 记一次Docker下安装Logstash+Elasticsearch+Kibana经历
- JAVA_WEB设计模式4
- Loaded plugins: fastestmirror -- Repodata is over 2 weeks old. Install yum-cron? Or run: yum makecac
- #85 Insert Node in a Binary Search Tree
- uva 12186 Another Crisis 树形DP
- phpcms常用变量
- Linux下时间编程(综合知识+综合编程):time,ctime,strftime,localtime,gmtime,gettimeofday
- [Java JVM] Hotspot GC研究- 什么是GC Root
- 笔试知识点记录
- centos7设置固定IP
- java平台的常用资源
- 文章标题