leetcode 701 二叉搜索树的插入操作 C++ 递归和迭代
生活随笔
收集整理的這篇文章主要介紹了
leetcode 701 二叉搜索树的插入操作 C++ 递归和迭代
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
迭代
class Solution { public:TreeNode* insertIntoBST(TreeNode* root, int val) {if(!root) return new TreeNode(val);TreeNode*cur=root;while(cur){if(val<cur->val){if(cur->left)cur=cur->left;else{cur->left=new TreeNode(val);break;}}else if(val>cur->val){if(cur->right)cur=cur->right;else{cur->right=new TreeNode(val);break;}}}return root;} };遞歸
class Solution { public:TreeNode* insertIntoBST(TreeNode* root, int val) {if(!root) return new TreeNode(val);else if(val>root->val) root->right=insertIntoBST(root->right,val);else root->left=insertIntoBST(root->left,val);return root;} };END
總結
以上是生活随笔為你收集整理的leetcode 701 二叉搜索树的插入操作 C++ 递归和迭代的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 简单了解一下ArcPy
- 下一篇: mysql字符集排序规则_Mysql 字