算法D17 | 二叉树4 | 110.平衡二叉树 257. 二叉树的所有路径 404.左叶子之和

详细布置 

迭代法,大家可以直接过,二刷有精力的时候 再去掌握迭代法。

110.平衡二叉树 (优先掌握递归)

再一次涉及到,什么是高度,什么是深度,可以巩固一下。

题目链接/文章讲解/视频讲解:代码随想录

Python递归版本:

class Solution:
    def get_height(self, root):
        if not root: return 0
        left = self.get_height(root.left)
        if left==-1: return -1
        right = self.get_height(root.right)
        if right==-1: return -1
        if abs(left-right)>1:
            return -1
        else:
          return 1 + max(left, right)

    def isBalanced(self, root: Optional[TreeNode]) -> bool:
        if self.get_height(root)==-1:
            return False
        else:
            return True

也可以把定义left 和判断left==-1写到一起(:=),效率无区别,学习新语法:

class Solution:
    def get_height(self, root):
        if not root: return 0
        if (left := self.get_height(root.left)) == -1: 
            return -1
        if (right := self.get_height(root.right)) == -1: 
            return -1
        if abs(left-right)>1:
            return -1
        else:
          return 1 + max(left, right)

    def isBalanced(self, root: Optional[TreeNode]) -> bool:
        return self.get_height(root)!=-1

C++递归:

C++写return if else可以很简洁。

class Solution {
public:
    int getHeight(TreeNode* root) {
        if (root==NULL) return 0;
        int left_height = getHeight(root->left);
        if (left_height==-1) return -1;
        int right_height = getHeight(root->right);
        if (right_height==-1) return -1;
        return (abs(left_height-right_height)>1)?-1:1+max(left_height, right_height);
    }
    bool isBalanced(TreeNode* root) {
        return getHeight(root)==-1? false: true;      
    }
};

257. 二叉树的所有路径 (优先掌握递归)  

这是大家第一次接触到回溯的过程, 我在视频里重点讲解了 本题为什么要有回溯,已经回溯的过程。 

如果对回溯 似懂非懂,没关系, 可以先有个印象。 

题目链接/文章讲解/视频讲解:代码随想录

Python递归:

路径是从root到leaf,所以采用前序遍历(中左右),由于是路径,所以遍历左右节点之后又回溯,只记录路径部分。

class Solution:
    def traversal(self, root, path, result):
        # 中
        path.append(str(root.val))
        if (not root.left) and (not root.right):
            spath = '->'.join(map(str, path))
            result.append(spath)
            return
        # 左
        if root.left:
            self.traversal(root.left, path, result)
            path.pop()
        # 右
        if root.right:
            self.traversal(root.right, path, result)
            path.pop()

    def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
        if not root: return []
        result = []
        path = []
        self.traversal(root, path, result)
        return result

C++递归:

注意traversal()函数传递参数的方式,vector<string>& 而非vector<string> 代表要修改传入的参数本身。

class Solution {
public:
    void traversal(TreeNode* root, vector<string>& result, vector<int>& path) {
        path.push_back(root->val); // 中
        if (root->left==NULL and root->right==NULL) {
            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 (root->left!=NULL) { // 左
            traversal(root->left, result, path); 
            path.pop_back();
        }
        if (root->right!=NULL) { // 右
            traversal(root->right, result, path);
            path.pop_back();
        }
    }
    vector<string> binaryTreePaths(TreeNode* root) {
        vector<string> result;
        vector<int> path;
        traversal(root, result, path);
        return result;    
    }
};

404.左叶子之和 (优先掌握递归)

其实本题有点文字游戏,搞清楚什么是左叶子,剩下的就是二叉树的基本操作。 

题目链接/文章讲解/视频讲解:代码随想录

Python递归:

class Solution:
    def sumOfLeftLeaves(self, root: Optional[TreeNode]) -> int:
        if not root: return 0
        if (not root.left) and (not root.right): return 0
        # 左
        left_value = self.sumOfLeftLeaves(root.left) 
        if root.left and (not root.left.left) and (not root.left.right):
            left_value = root.left.val
        # 右
        right_value = self.sumOfLeftLeaves(root.right)
        # 中
        result = left_value + right_value
        return result

C++递归:

class Solution {
public:
    int sumOfLeftLeaves(TreeNode* root) {
        if (root==NULL) return 0;
        if (root->left==NULL && root->right==NULL) return 0;
        int leftValue = sumOfLeftLeaves(root->left);
        if (root->left!=NULL && root->left->left==NULL && root->left->right==NULL) {
            leftValue = root->left->val;
        }
        int rightValue = sumOfLeftLeaves(root->right);
        int result = leftValue + rightValue;
        return result;
    }
};

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值