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;
    }
    
};

バイナリツリーの最大深さ

最大 (左のノードの数、右のノードの数) + ルート ノード

int maxDepth(TreeNode* root) {
        if(!root) return 0;
        return max(maxDepth(root->left), maxDepth(root->right))+1;
    }

 二分木で合計が特定の値になるパス (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);
    }
};

おすすめ

転載: blog.csdn.net/qq_54809548/article/details/131079969