110. 平衡二叉树
思路:每个结点都判断,左右两分支的高度差是否符合,若不符合,把全局变量标记为false;
代码录思路:
class Solution {
boolean res = true;
public boolean isBalanced(TreeNode root) {
height(root);
return res;
}
int height(TreeNode root) {//获得该节点的高度
if(res == false) return 0;
if(root == null) return 0;
int left = height(root.left);
int right = height(root.right);
int difference = left>right?left-right:right-left;
if(difference > 1) res = false;
return left>right?left+1:right+1;
}
}
257. 二叉树的所有路径
思路:
class Solution {
List<String> list = new ArrayList<String>();
public List<String> binaryTreePaths(TreeNode root) {
ArrayList<Integer> map = new ArrayList<>();
f(root, map);
return list;
}
void f(TreeNode root,ArrayList<Integer> map ) {
if(root.left == null && root.right == null) {
map.add(root.val);
list.add(f2(map));
map.remove(map.size()-1);
}
if(root.left != null) {
map.add(root.val);
f(root.left, map);
map.remove(map.size()-1);
}
if(root.right != null) {
map.add(root.val);
f(root.right, map);
map.remove(map.size()-1);
}
}
String f2(ArrayList<Integer> map) {
String res = "";
for(Integer num : map) {
res = res + Integer.toString(num) +"->";
}
if (res.length() >= 2) {
res = res.substring(0, res.length() - 2);
}
return res;
}
}
404. 左叶子之和
代码录思路:递归,后序遍历。先处理空结点和叶子结点,都返回0。然后处理非叶子,分别递归该结点的左右子结点,若该结点就有左叶子,则左边的值就设置为左叶子的值。然后返回左右的和。
class Solution {
public int sumOfLeftLeaves(TreeNode root) {
//空结点返回0
if(root == null) return 0;
//自己是叶子结点,返回0,因为自己不能判断自己是不是左叶子
if(root.left == null && root.right == null) return 0;
//非空非叶子结点的处理
//递归左子树
int leftNum = sumOfLeftLeaves(root.left);
//如果左子树为左叶子,就返回左叶子
if(root.left != null &&root.left.left == null && root.left.right == null)
leftNum = root.left.val;
int rightNum = sumOfLeftLeaves(root.right);
return leftNum+rightNum;
}
}
222. 完全二叉树的节点个数
我的思路:初始化一个全局变量,若该结点非空,则++;
class Solution {
int num = 0;
public int countNodes(TreeNode root) {
if(root == null) return 0;
num++;
countNodes(root.left);
countNodes(root.right);
return num;
}
}
代码录思路:
class Solution {
public int countNodes(TreeNode root) {
if(root == null) return 0;
int left = countNodes(root.left);
int right = countNodes(root.right);
return left + right + 1;
}
}
鉴于作者水平有限,文章可能存在错误
如有指正,十分感谢