在二叉查找树中插入节点-LintCode

来源:互联网 发布:mac版的photoshop cc 编辑:程序博客网 时间:2024/06/08 13:49

给定一棵二叉查找树和一个新的树节点,将节点插入到树中。
你需要保证该树仍然是一棵二叉查找树。
样例:
给出如下一棵二叉查找树,在插入节点6之后这棵二叉查找树可以是这样的:
这里写图片描述

#ifndef C85_H#define C85_H#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:    /**    * @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;        int i = 0;        TreeNode *p = root,*q=root;        while (p != NULL)        {            if (p->val < node->val)            {                q = p;                p = p->right;                i = 0;            }            else            {                q = p;                p = p->left;                i = 1;            }        }        if (i == 0)            q->right = new TreeNode(node->val);        else            q->left = new TreeNode(node->val);        return root;    }};#endif
原创粉丝点击