平衡二叉树(Python and C++算法)

题目:

输入一棵二叉树的根节点,判断该树是不是平衡二叉树。如果某二叉树中任意节点的左右子树的深度相差不超过1,那么它就是一棵平衡二叉树。

限制:

1 <= 树的结点个数 <= 10000

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/ping-heng-er-cha-shu-lcof

思路:

  判断的过程中需要计算树的深度,以某节点为父节点的树深度=max(左子树的深度,右子树的深度)+1。

  采用后序遍历的方法,从底至顶判断,先遍历左右子节点得出子节点的深度,判断当前子树是否符合要求:

    如果符合要求则返回当前子树的深度;

    如果不符合要求则返回-1,若发现某子树深度为-1,直接返回相当于进行剪枝。

Python解法:

 1 class TreeNode:
 2     def __init__(self, x):
 3         self.val = x
 4         self.left = None
 5         self.right = None
 6 
 7 class Solution:
 8     def isBalanced(self, root: TreeNode) -> bool:
 9         def recur(root):
10             if root is None:  # 递归终止条件
11                 return 0
12             leftDepth = recur(root.left)  # 递归左子树
13             if leftDepth == -1:
14                 return -1
15             rightDepth = recur(root.right)  # 递归右子树
16             if rightDepth == -1:
17                 return -1
18             if abs(leftDepth-rightDepth) <= 1:
19                 return max(leftDepth, rightDepth) + 1
20             else:
21                 return -1
22         return recur(root) != -1

C++解法:

 1 struct TreeNode {
 2     int val;
 3     TreeNode *left;
 4     TreeNode *right;
 5     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 6 };
 7  
 8 class Solution {
 9 public:
10     bool isBalanced(TreeNode* root) {
11         return recur(root) != -1;
12     }
13     int recur(TreeNode *root) {
14         if(root == NULL)
15             return 0;
16         int leftDepth = recur(root -> left);
17         if(leftDepth == -1)
18             return -1;
19         int rightDepth = recur(root -> right);
20         if(rightDepth == -1)
21             return -1;
22         if(abs(leftDepth - rightDepth) <= 1)
23             return max(leftDepth, rightDepth) + 1;
24         else
25             return -1;
26     }
27 };
posted @ 2020-07-31 17:20  孔子?孟子?小柱子!  阅读(237)  评论(0编辑  收藏  举报