标签:abs 题目 als lse 左右 tree math offer max
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
可以从根节点开始遍历每一个节点,求得节点左右子树的最大高度,判断是不是平衡二叉树。这样做的问题在于会重复遍历节点,造成不必要的浪费。
所以可以采用后续遍历来求解此题,判断子树是否是平衡二叉树,如果是,就返回子树的最大高度,不是的话,就中止遍历,这样做的话每个节点只访问一遍。
C++
class Solution { public: bool IsBalanced_Solution(TreeNode* pRoot) { if(getHeight(pRoot) == -1) return false; return true; } int getHeight(TreeNode* root){ if(root == nullptr) return 0; int leftHeight = getHeight(root->left); if(leftHeight == -1) return -1; int rightHeight = getHeight(root->right); if(rightHeight == -1) return -1; return abs(leftHeight - rightHeight) <= 1 ? 1 + max(leftHeight, rightHeight): -1; } };
Java
public class Solution { public boolean IsBalanced_Solution(TreeNode root) { if(getHeight(root) == -1) return false; return true; } public int getHeight(TreeNode root){ if(root == null) return 0; int leftHeight = getHeight(root->left); if(leftHeight == -1) return -1; int rightHeight = getHeight(root->right); if(rightHeight == -1) return -1; return Math.abs(leftHeight - rightHeight) <= 1 ? 1 + Math.max(leftHeight, rightHeight): -1; } }
标签:abs 题目 als lse 左右 tree math offer max
原文地址:https://www.cnblogs.com/silentteller/p/12051453.html