一、求二叉树的深度
// 1.广度优先搜索(BFS):
int maxDepth(TreeNode* root){
queue<TreeNode*> q;
if(root) q.push(root);
int Tdepth = 0;
while(!q.empty()){
for(int i=q.size()-1;i>=0;i--){
TreeNode* cur = q.front();
q.pop();
if(cur->left) q.push(cur->left);
if(cur->right)q.push(cur->right);
}
++Tdepth;
}
return Tdepth;
}
//2.深度优先遍历/递归法(DFS):
int maxDepth(TreeNode* root){
if(!root) return 0;
return max(maxDepth(root->left),maxDepth(root->right))+1;
}
二、二叉搜索树中搜索某值
//1.递归法
TreeNode* searchBST(TreeNode* root, int val){
if(!root) return NULL;
if(root->val==val) return root;
if(root->val>val){
return searchBST(root->left,val);
}else{
return searchBST(root->right,val);
}
}
//2.迭代法
TreeNode* searchBST(TreeNode* root, int val){
while(root){
if(val==root->val)return root;
else if(val<root->val)root=root->left;
else root= root->right;
}
return NULL;
}
三、前序/中序/后序遍历
先序遍历:
vector<int> res;
vector<int> preorderTraversal(TreeNode* root){
stack<TreeNode*> st;
TreeNode* p=root;
while(p||!st.empty()){
if(p){
res.push_back(p->val);
st.push(p);
p=p->left;
}else{
p=st.top();
st.pop();
p=p->right;
}
}
return res;
}
中序遍历:
vector<int> res;
vector<int> inorderTraversal(TreeNode* root){
stack<TreeNode*> st;
TreeNode* p = root;
while(p||!st.empty()){
if(p){
st.push(p);
p=p->left;
}else{
p=st.top();
st.pop();
res.push_back(p->val);
p=p->right;
}
}
return res;
}
后序遍历:
vector<int>res;
vector<int> postorderTraversal(TreeNode* root){
stack<TreeNode*>st;
TreeNode *p=root,*pre=NULL;
while(p||!st.empty()){
if(p){
st.push(p);
p=p->left;
}else{
p=st.top();
if(p->right&&pre!=p->right){
p=p->right;
}else{
res.push_back(p->val);
st.pop();
pre=p;
p=NULL;
}
}
}
return res;
}
四、二叉搜索树中插入节点
递归法:
class Solution {
public:
TreeNode* insertIntoBST(TreeNode* root, int val) {
if (!root) return new TreeNode(val);
if (val < root->val) root->left = insertIntoBST(root->left, val);
else root->right = insertIntoBST(root->right, val);
return root;
}
};
迭代法:
class Solution{
public TreeNode* insertIntoBST(TreeNode* root,int val){
if(!root) return new TreeNode(val);
TreeNode *p=new TreeNode(val);
TreeNode *head=root;
while(root){
if(val<root->val){
if(root->left){
root=root->left;
}else{
root->left=p;
break;
}
}else if(val>root->val){
if(root->right){
root=root->right;
}else{
root->right=p;
break;
}
}
}
return head;
}
};
}