day14--二叉树

 按之字形顺序打印二叉树

 

 层次遍历+控制方向

/*
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);
    }
};

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值