LintCode 85. 在二叉查找樹中插入節點
阿新 • • 發佈:2018-01-28
插入 ram solution treenode insert bsp ins fin eno
題目:
給定一棵二叉查找樹和一個新的樹節點,將節點插入到樹中。
你需要保證該樹仍然是一棵二叉查找樹
樣例
給出如下一棵二叉查找樹,在插入節點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 hereif(root==NULL) { root=node; return node; } TreeNode* p=root; while(p!=NULL) { if(node->val<p->val) { if(p->left==NULL) { p->left=node;return root; } else { p=p->left; } } else { if(p->right==NULL) { p->right=node; return root; } else { p=p->right; } } } return NULL; } };
LintCode 85. 在二叉查找樹中插入節點