Leetcode 110.平衡二叉树
1)平衡二叉树:任何一个节点的左节点和右节点的高度差不超过1;
2)要明确高度和深度的区别;
3) 其实根节点的高度就是这棵树的最大深度。
class Solution {
public boolean isBalanced(TreeNode root) {
if (root == null) {
return true;
}
return getHeight(root) != -1;
}
public int getHeight(TreeNode root) {
//当根节点为空时,返回高度为0
if (root == null) {
return 0;
}
//记录高度差,初始化为0
int diffHeight = 0;
//遍历左几点
int leftHeight = getHeight(root.left);
if (leftHeight == -1) {
return -1;
}
//遍历右节点
int rightHeight = getHeight(root.right);
//如果等于-1,则向上返回-1
if (rightHeight == -1) {
return -1;
}
//在后序位置获取高度差
diffHeight = Math.abs(leftHeight - rightHeight);
if (diffHeight > 1) {
return -1;
}
//满足平衡条件,最终获取根节点的高度,就是叶子结点的最大深度
return Math.max(leftHeight, rightHeight) + 1;
}
}
Leetcode 257. 二叉树的所有路径
1)使用字符串的作为局部变量时,字符串是不可变的数据类型,返回到上一层节点时,之前的字符串变量path并没有改变,所以不需要回溯;这也会导致修改字符串时会产生新的对象,会新建一个新的内存空间;
2)可以使用stringBuilder去,减少内存空间的消耗。
class Solution {
List<String> res = new ArrayList<>();
public List<String> binaryTreePaths(TreeNode root) {
if (root == null) {
return res;
}
String path = "";
tranverse(root, path);
return res;
}
public void tranverse(TreeNode root, String path) {
if (root == null) {
return;
}
path = path + root.val;
if (root.left == null && root.right == null) {
res.add(path);
//结束,返回到上一级
return;
}
path = path + "->";
tranverse(root.left, path);
tranverse(root.right, path);
}
}
Method2: 用StringBuilder来作为path变量
class Solution {
List<String> res = new ArrayList<>();
public List<String> binaryTreePaths(TreeNode root) {
if (root == null) {
return res;
}
// String path = "";
//tranverse(root, path);
tranverse(root, new StringBuilder());
return res;
}
public void tranverse(TreeNode root, StringBuilder path) {
if (root == null) {
return;
}
int beforeLength = path.length();
if (beforeLength > 0) {
path.append("->");
}
path.append(root.val);
if (root.left == null && root.right == null) {
res.add(path.toString());
}
tranverse(root.left, path);
tranverse(root.right, path);
//backtrack
path.setLength(beforeLength);
}
}
leetcode 404.左叶子之和
看题目要求:
A leaf is a node with no children.
A left leaf is a leaf that is the left child of another node
所以明确表示出左叶子节点之后,正常遍历就行
class Solution {
int sum = 0;
public int sumOfLeftLeaves(TreeNode root) {
if (root == null) {
return 0;
}
if (root.left == null && root.right == null) {
return 0;
}
tranverse(root);
return sum;
}
public void tranverse(TreeNode root) {
if (root == null) {
return;
}
tranverse(root.left);
tranverse(root.right);
if (root.left != null && root.left.left == null && root.left.right == null) {
sum += root.left.val;
}
}
}