programming review (c++): (2)binary tree, BFS, DFS, recursive, non-recursive
2016-03-13 17:43
330 查看
1.二叉树定义
2.遍历
a.递归先序:
PS:
递归变量传递的几种方式:
参数里,比如可以以此标记每个node的深度;
return,适合做累计操作,例子:
参数里加&,贯穿型变量。
b.DFS/非递归先序
c.BFS
变形,按层action:
// Definition for a binary tree node. struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} };
2.遍历
a.递归先序:
//递归先序: 中左右。PS:中序-左中右,后序-左右中,调换cout的位置即可 void NLR(TreeNode* T) { if(T!=NULL){ cout<<T->val; NLR(T->left); NLR(T->right); } return; }
PS:
递归变量传递的几种方式:
参数里,比如可以以此标记每个node的深度;
return,适合做累计操作,例子:
int maxDepth(TreeNode *root) //求最大深度:反过来算+max,符合逻辑 { return root == NULL ? 0 : max(maxDepth(root -> left), maxDepth(root -> right)) + 1; }
参数里加&,贯穿型变量。
b.DFS/非递归先序
//DFS-非递归先序:中左右 void depthFirstSearch(TreeNode* root){ stack<TreeNode *> nodeStack; //stack nodeStack.push(root); TreeNode *node; while(!nodeStack.empty()){ node = nodeStack.top(); cout<<node->val; //action nodeStack.pop(); if(node->right!=null){ nodeStack.push(node->right); } if(node->left!=null){ nodeStack.push(node->left); } } }
c.BFS
//BFS void BFS(TreeNode* root){ queue<TreeNode *> nodeQueue; //queue nodeQueue.push(root); TreeNode *node; while(!nodeQueue.empty()){ node = nodeQueue.front(); cout<<node->val; //action nodeQueue.pop(); if(node->left!=null){ nodeQueue.push(node->left); } if(node->right!=null){ nodeQueue.push(node->right); } } }
变形,按层action:
int maxDepth(TreeNode* root) { int res=0; if(root){ queue<TreeNode*> mq; mq.push(root); TreeNode* node; while(!mq.empty()){ res++; for(int i=0,n=mq.size();i<n;i++){ node=mq.front(); mq.pop(); if(node->left!=NULL) mq.push(node->left); if(node->right!=NULL) mq.push(node->right); } } } return res; }
相关文章推荐
- C++中const的问题(刷题后感)
- C++_动态存储空间的分配和释放
- leetcode 121.Best Time to Buy and Sell Stock 股票买卖最佳时间
- C++第一次上机实验-1-2
- Effective C++ 条款18
- 俄罗斯方块的c语言基本实现
- 详解C++中如何将构造函数或析构函数的访问权限定为private
- c++第2次实验(循环)
- VC++制作DLL具体解释
- C++中引用的详解
- 2012年第三届蓝桥杯试题(C/C++本科B组)
- stl之空间配置器Allocator
- 类的对象和类的指针的区别
- C++的静态联编和动态联编
- 2048的c语言实现
- 随机函数rand()和srand()(c++)
- 金磊c++
- C++上机报告(2)
- c语言和c++有什么区别
- c++不同继承方式的访问权限