标签:else val 中序 pre search col color 二叉树 span
1.正常递归
1 TreeNode* searchBST(TreeNode* root, int val) { 2 if (!root) 3 return nullptr; 4 if (val > root->val) 5 { 6 root = searchBST(root->right, val); 7 } 8 else if (val < root->val) 9 { 10 root = searchBST(root->left, val); 11 } 12 return root; 13 }
2.中序递归
1 TreeNode* searchBST(TreeNode* root, int val) { 2 if (!root) 3 return nullptr; 4 TreeNode* res = searchBST(root->left, val); 5 if (res) 6 return res; 7 else if (root->val > val) 8 return nullptr; 9 else if (root->val == val) 10 return root; 11 TreeNode* res = searchBST(root->right, val); 12 return res; 13 }
3.迭代
1 TreeNode* searchBST(TreeNode* root, int val) { 2 while (root) 3 { 4 if (root->val > val) 5 root = root->left; 6 else if (root->val < val) 7 root = root->right; 8 else 9 return root; 10 } 11 return root; 12 }
标签:else val 中序 pre search col color 二叉树 span
原文地址:https://www.cnblogs.com/zouma/p/11566861.html