二叉树算法练习递归类型汇总
递归类型 按照编程技巧分啪 一、将复杂问题分解成两个子问题 1、平衡二叉树( LeetCode题库110题 ) 自上而下 :算每个节点的平衡因子(即左右子树的高度差),判断是否满足条件。 可以分成两个子问题:求树的高度,和遍历树判断每个节点的是否满足条件 class Solution { public boolean isBalanced(TreeNode root) { if(root == null) { return true; }else { //判断根结点是否满足平衡因子 int ldepth = depth(root.left); int rdepth = depth(root.right); System.out.println(ldepth + " " + rdepth); if(Math.abs(ldepth - rdepth) > 1) { return false; } //判断左子树是否满足平衡因子 if(!isBalanced(root.left)) { return false; } //判断右子树是否满足平衡因子 if(!isBalanced(root.right)) { return false; } return true; } } private int depth(TreeNode root) { int l = 0; int r = 0;