11.7算法(树Ⅲ)

6.10左叶子之和

class Solution {
public:
    int sumOfLeftLeaves(TreeNode* root) {
        if(root==NULL) return 0;
        int leftval = sumOfLeftLeaves(root->left);
        if(root->left&&!root->left->left&&!root->left->right)//当前结点左子树存在且左子树的左右结点
            leftval = root->left->val;//结点满足条件才能相加
        int rightval = sumOfLeftLeaves(root->right);
        int sum = leftval+rightval;
        return sum;
    }
};

6.11找树左下角的值

class Solution {
public:
    int result;
    int maxdepth=0;
    void findamxleft(TreeNode* node,int depth){
        if(!node->left&&!node->right){//叶子结点才进行操作
            if(depth>maxdepth){
                result = node->val;
                maxdepth = depth;
            }
            return;
        }
        if(node->left){
            depth++;
            findamxleft(node->left,depth);
            depth--;//向上回溯的时候需要树高减一
        }
        if(node->right){
            depth++;
            findamxleft(node->right,depth);
            depth--;
        }
        return;
    }

    int findBottomLeftValue(TreeNode* root) {
        findamxleft(root,0);
        return result;
    }
};

6.12路径总和

#include<utility>
class Solution {
public:
    bool hasPathSum(TreeNode* root, int targetSum) {
        if(!root) return false;
        stack<pair<TreeNode*,int>> st;
        st.push(pair<TreeNode*,int>(root,root->val));//将根节点和其值压入栈
        while(!st.empty()){//非递归先序
            pair<TreeNode*,int> node = st.top();//node指向栈顶元素
            st.pop();
            if(!node.first->left&&!node.first->right&&node.second==targetSum) return true;//满足叶子结点且栈顶的值满足target
            if(node.first->left)
                st.push(pair<TreeNode*,int>(node.first->left,node.second+node.first->left->val));//左节点存在压入栈中,同时相加值
            if(node.first->right)
                st.push(pair<TreeNode*,int>(node.first->right,node.second+node.first->right->val));
        }
        return false;
    }
};

6.13从中序与后序遍历序列构造二叉树

class Solution {
public:
    TreeNode* inpostbuildtree(vector<int>& inorder,vector<int>& postorder,int l1,int h1,int l2,int h2){//l1,h1为中序的第一个和最后一个;l2,h2为后序的第一个和最后一个
        if(inorder.size()==0) return NULL;
        int rootvalue = postorder[h2];
        TreeNode* root = new TreeNode(rootvalue);
        int i=0;
        while(inorder[i]!=rootvalue)
            i++;
        int llen = i-l1;
        int rlen = h1-i;
        if(llen)
            root->left = inpostbuildtree(inorder,postorder,l1,l1+llen-1,l2,l2+llen-1);
        else
            root->left = NULL;
        if(rlen)
            root->right = inpostbuildtree(inorder,postorder,l1+llen+1,h1,h2-rlen,h2-1);
        else
            root->right = NULL;
        return root;

    }
    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
        int l1=0,h1 = inorder.size()-1;
        int l2 = 0,h2 = postorder.size()-1;
        return inpostbuildtree(inorder,postorder,l1,h1,l2,h2);
    }
};
posted @ 2023-11-10 11:08  Ref-rain-  阅读(23)  评论(0)    收藏  举报