按之字形顺序打印二叉树
层次遍历+控制方向
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
*/
#include <queue>
#include <vector>
class Solution {
public:
vector<vector<int> > Print(TreeNode* pRoot) {
vector<vector<int>> res;
if(!pRoot) return res;
queue<TreeNode*> q{
{pRoot}};
bool left=true;//从左到右,false:从右到左
while(!q.empty()){
int size=q.size();
vector<int> level(size);
for(int i=0; i<size; i++){
int id=left? i:size-i-1;//控制方向
TreeNode* t=q.front(); q.pop();
level[id]=t->val;
if(t->left) q.push(t->left);
if(t->right) q.push(t->right);
}
res.push_back(level);
left=!left;//改变遍历方向
}
return res;
}
};
二叉树的最大深度
max(左节点数,右节点数)+根节点
int maxDepth(TreeNode* root) {
if(!root) return 0;
return max(maxDepth(root->left), maxDepth(root->right))+1;
}
二叉树中和为某一值的路径(一)
bool hasPathSum(TreeNode* root, int sum) {
if(!root) return false;
// 合为sum,并且为叶子节点(无左右节点)
if(root->val==sum && !root->left && !root->right) return true;
return hasPathSum(root->left, sum-root->val) || hasPathSum(root->right, sum-root->val);
}
对称的二叉树
使用队列(非递归方法)
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
*/
#include <queue>
class Solution {
public:
bool isSymmetrical(TreeNode* pRoot) {
if(!pRoot) return true;
queue<TreeNode*>q;
q.push(pRoot->left), q.push(pRoot->right);
while(!q.empty()){
TreeNode* l=q.front(); q.pop();
TreeNode* r=q.front(); q.pop();
if(!l && !r) continue;
if(!l || !r || l->val!=r->val) return false;
q.push(l->left); q.push(r->right);
q.push(l->right); q.push(r->left);
}
return true;
}
};
递归方法
class Solution {
public:
bool istrue(TreeNode* l, TreeNode* r){
if(!l && !r) return true;
if(!l || !r || l->val!=r->val) return false;
return istrue(l->left,r->right) && istrue(l->right, r->left);
}
bool isSymmetrical(TreeNode* pRoot) {
if(!pRoot) return true;
return istrue(pRoot->left, pRoot->right);
}
};