day17 平衡二叉树 二叉树的所有路径 左叶子之和

题目1:110 平衡二叉树

题目链接:110 平衡二叉树

题意

判断二叉树是否为平衡二叉树(每个节点的左右两个子树的高度差绝对值不超过1)

递归遍历

递归三部曲

1)确定递归函数的参数和返回值

2)确定终止条件

3)确定单层递归逻辑

代码

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int getheight(TreeNode* node){
        //终止条件
        if(node==NULL) return 0;
        int result = 0;//result一定要提前定义,是一个全局变量,最终return
        //单层递归逻辑 后序遍历  左右中
        int leftheight = getheight(node->left);//左
        if(leftheight==-1) return -1;
        int rightheight = getheight(node->right);//右
        if(rightheight==-1) return -1;
        //中
        if(abs(rightheight-leftheight)>1) return -1;
        else{
            result = 1 + max(leftheight,rightheight);
        }
        return result;
    }
    bool isBalanced(TreeNode* root) {
        int result = getheight(root);
        if(result==-1) return false;
        else return true;
    }
};

题目2:257 二叉树的所有路径

题目链接:257 二叉树的所有路径

题意

根据二叉树的根节点root,返回所有从根节点到叶子节点的路径(顺序任意)

递归

递归三部曲

1)确定递归函数的参数和返回值

2)确定终止条件

3)确定单层递归逻辑

代码

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    void traversal(TreeNode* node,vector<int>& path,vector<string>& result){
        //中 加入后面终止条件的叶子节点
        path.push_back(node->val);//node->val是整型的数字
        //终止条件,遇到叶子节点就终止
        if(node->left==NULL && node->right==NULL){
            //将path放入到result中,注意转换类型,添加->
            string spath;
            for(int i=0;i<path.size()-1;i++){
                spath += to_string(path[i]);
                spath += "->";
            }
            spath += to_string(path[path.size()-1]);//加入最后一个,因为后面没有->,所以单独加入
            result.push_back(spath);
            return;
        }
        //单层递归逻辑  前序遍历   中左右
        if(node->left){
            traversal(node->left,path,result);//左
            path.pop_back();//回溯
        }
        if(node->right){
            traversal(node->right,path,result);//右
            path.pop_back();//回溯
        } 
    }   
    vector<string> binaryTreePaths(TreeNode* root) {
        vector<int> path;
        vector<string> result;
        if(root==NULL) return result;
        traversal(root,path,result);
        return result;
    }
};
隐藏回溯

使用的是 string path,这里并没有加上引用& ,即本层递归中,path + 该节点数值,但该层递归结束,上一层path的数值并不会受到任何影响

代码

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    void traversal(TreeNode* node,string path,vector<string>& result){
        //中 加入后面终止条件的叶子节点
        path += to_string(node->val);//node->val是整型的数字
        //终止条件,遇到叶子节点就终止
        if(node->left==NULL && node->right==NULL){
            //将path放入到result中,注意转换类型,添加->
            result.push_back(path);
            return;
        }
        //单层递归逻辑  前序遍历   中左右
        if(node->left){
            traversal(node->left,path+"->",result);//左
            //path.pop_back();//回溯
        }
        if(node->right){
            traversal(node->right,path+"->",result);//右
            //path.pop_back();//回溯
        } 
    }   
    vector<string> binaryTreePaths(TreeNode* root) {
        string path;
        vector<string> result;
        if(root==NULL) return result;
        traversal(root,path,result);
        return result;
    }
};
非隐藏回溯

代码

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    void traversal(TreeNode* node,string path,vector<string>& result){
        //中 加入后面终止条件的叶子节点
        path += to_string(node->val);//node->val是整型的数字
        //终止条件,遇到叶子节点就终止
        if(node->left==NULL && node->right==NULL){
            //将path放入到result中,注意转换类型,添加->
            result.push_back(path);
            return;
        }
        //单层递归逻辑  前序遍历   中左右
        if(node->left){
            path = path + "->";
            traversal(node->left,path,result);//左
            path.pop_back();//回溯 >
            path.pop_back();//回溯 -
        }
        if(node->right){
            path = path + "->";
            traversal(node->right,path,result);//右
            path.pop_back();//回溯  >
            path.pop_back();//回溯  -
        } 
    }   
    vector<string> binaryTreePaths(TreeNode* root) {
        string path;
        vector<string> result;
        if(root==NULL) return result;
        traversal(root,path,result);
        return result;
    }
};

题目3:404  左叶子之和

题目链接:404 左叶子之和

题意

返回所有左叶子之和

一定要是叶子节点  且是父节点的左孩子,因此必须通过节点的父节点判断当前节点是否为左叶子

递归

递归三部曲

1)确定递归函数的参数和返回值

2)确定终止条件

3)确定单层递归逻辑

代码

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int sumOfLeftLeaves(TreeNode* root) {
       //终止条件
       if(root==NULL) return 0;
       if(root->left==NULL && root->right==NULL) return 0;
       //单层递归逻辑  后序遍历  左右中
       //左
       int leftnum = sumOfLeftLeaves(root->left);
       if(root->left!=NULL && root->left->left==NULL && root->left->right==NULL) 
       leftnum = root->left->val;
       //右
       int rightnum = sumOfLeftLeaves(root->right);
       //中
       int sum = leftnum + rightnum;
       return sum;
    }
};

迭代

因为用递归可以做的,栈也可以 

这里栈只是一个容器,换成队列也可 

前序遍历

代码

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int sumOfLeftLeaves(TreeNode* root) {
       stack<TreeNode*> st;
       if(root!=NULL) st.push(root);
       int sum = 0;
       while(!st.empty()){
           TreeNode* node = st.top();
           st.pop();
           if(node->left!=NULL && node->left->left==NULL && node->left->right==NULL){
               sum += node->left->val;
           }
           if(node->left) st.push(node->left);
           if(node->right) st.push(node->right);
       }
       return sum;
    }
};
后序遍历
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int sumOfLeftLeaves(TreeNode* root) {
       stack<TreeNode*> st;
       if(root!=NULL) st.push(root);
       int sum = 0;
       while(!st.empty()){
           TreeNode* node = st.top();
           st.pop();
           if(node->left) st.push(node->left);
           if(node->right) st.push(node->right);
           if(node->left!=NULL && node->left->left==NULL && node->left->right==NULL){
               sum += node->left->val;
           }
       }
       return sum;
    }
};

  • 9
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
首先,我们需要了解什么是扩展二叉树。扩展二叉树是一种二叉树的表示方法,其中每个非叶子节点都有两个子节点,但其中一个或两个子节点可以为空。因此,扩展二叉树的前序序列可以被表示为一个字符串,其中空节点用字符“#”表示。例如,扩展二叉树“1(2(4(#)(#))(5(#)(#)))”可以表示为前序序列“124##5##”。 现在我们来考虑如何构建二叉树。我们可以使用递归的方法来构建二叉树,每次递归都处理当前节点的子树和右子树。具体来说,我们可以先读取前序序列中的下一个字符,如果当前字符是“#”,则表示该节点为空;否则,我们可以将该字符转换为数字并创建一个新节点,然后递归构建该节点的子树和右子树。 下面是 Python 代码实现: ``` python class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def buildTree(preorder): def helper(): val = preorder.pop(0) if val == '#': return None node = TreeNode(int(val)) node.left = helper() node.right = helper() return node return helper() ``` 接下来,我们需要计算给定二叉树的所有叶子之和叶子是指没有右子树的子树节点。因此,我们可以使用递归的方法遍历整个二叉树,在遍历的过程中累加所有叶子节点的值。具体来说,对于每个节点,我们将其子节点的值加入结果中,然后递归处理其子树和右子树。 下面是 Python 代码实现: ``` python def sumOfLeftLeaves(root): def helper(node, is_left): if not node: return 0 if not node.left and not node.right and is_left: return node.val return helper(node.left, True) + helper(node.right, False) return helper(root, False) ``` 完整代码如下: ``` python class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def buildTree(preorder): def helper(): val = preorder.pop(0) if val == '#': return None node = TreeNode(int(val)) node.left = helper() node.right = helper() return node return helper() def sumOfLeftLeaves(root): def helper(node, is_left): if not node: return 0 if not node.left and not node.right and is_left: return node.val return helper(node.left, True) + helper(node.right, False) return helper(root, False) preorder = '1(2(4(#)(#))(5(#)(#)))' root = buildTree(list(preorder)) print(sumOfLeftLeaves(root)) # 输出 4 ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值