JZ79 判断是不是平衡二叉树 ⭐
思路一:记录depth
public class Solution {
public boolean IsBalanced_Solution (TreeNode pRoot) {
if (pRoot == null) return true;
if (depth(pRoot.right) == depth(pRoot.left) ||
depth(pRoot.right) - depth(pRoot.left) == 1 ||
depth(pRoot.left) - depth(pRoot.right) == 1)
return IsBalanced_Solution(pRoot.left) & IsBalanced_Solution(pRoot.right);
else return false;
}
public int depth(TreeNode root) {
if (root == null) return 0;
return 1 + Math.max(depth(root.left), depth(root.right));
}
}
思路二 dfs+递归后序遍历
public class Solution {
public static boolean flag = true;
public boolean IsBalanced_Solution (TreeNode pRoot) {
// dfs、递归后序遍历
dfs(pRoot);
return flag;
}
public static int dfs(TreeNode p) {
// 递归终止条件
if (p == null || flag == false) return 0; // 优化
int leftHeight = dfs(p.left);
int rightHeight = dfs(p.right);
// 本层递归逻辑
if ((leftHeight - rightHeight) > 1 || (rightHeight - leftHeight) > 1) {
flag = false;
return 0;
}
return leftHeight > rightHeight ? (leftHeight + 1) : (rightHeight + 1);
}
}
JZ8 二叉树的下一个结点 ⭐ ⭐ 31%
思路:
// 中序遍历下某节点的下一个节点
// 1.该节点没有右孩子,且该节点是其父节点的左孩子,那么他的父节点便是下一个节点
// 2.该节点没有右孩子,且该节点是其父节点的右孩子,那么迭代从他的父亲节点开始,
// 一直到节点是其父亲节点的左孩子,回到1的情况
// 3.该节点有右孩子,那么右孩子最左端的节点是下一个节点
1和2写到一个if里面
public class Solution {
public TreeLinkNode GetNext(TreeLinkNode pNode) {
if (pNode.right == null) {
while (pNode.next != null && pNode.next.left != pNode) { // 情况2
pNode = pNode.next;
}
return pNode.next;
}
pNode = pNode.right;
while (pNode.left != null) {
pNode = pNode.left;
}
return pNode;
}
}
JZ28 对称的二叉树 ⭐
判断是否是对称二叉树
当前节点, 左子树的左子树与右子树的右子树比较,左子树的右子树与右子树的左子树比较。
public class Solution {
public boolean isSymmetrical (TreeNode pRoot) {
if (pRoot == null) return true;
return issame(pRoot.left, pRoot.right);
}
public boolean issame(TreeNode r1, TreeNode r2) {
if (r1 == null && r2 == null) {
return true;
}
if (r1 == null || r2 == null) {
return false;
}
if (r1.val != r2.val) {
return false;
}
return issame(r1.left, r2.right) && issame(r1.right, r2.left);
}
}