LeetCode[110]平衡二叉树
思路:
本题解法依旧是后序遍历,采用左右根来解决,如果你要采用前序遍历什么的,你需要先计算根节点,那根节点的计算又要计算子节点,然后再递归左右,这样子节点就会被重复计算,对时间复杂度来说不太友好,属于O(nlog(n))时间复杂度。
但采用后序遍历就不一样了,只需要把每个节点都遍历一下就能得出答案,所以时间复杂度为O(n), 高下立判
代码:
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode() {}* TreeNode(int val) { this.val = val; }* TreeNode(int val, TreeNode left, TreeNode right) {* this.val = val;* this.left = left;* this.right = right;* }* }*/
class Solution {public boolean isBalanced(TreeNode root) {return getHeight(root) != -1;}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;if (Math.abs(leftHeight - rightHeight) > 1) {return -1;}return Math.max(leftHeight, rightHeight) + 1;}
}