LeetCode110.平衡二叉树
class Solution { public int getMax(int a , int b){ return a>b ? a : b; } public int getHide(TreeNode root){ if(root == null){ return 0; } /** 要注意平衡二叉树的判断不仅仅只是判断根节点,在孩子节点中可能就已经判断出来不是平衡二叉树,也就是left/rightHide == -1 ,此时要加判断逻辑,直接返回-1,如果不加这层逻辑,就会把-1当做left/righthide 继续去判断当前节点的高度。 */ int leftHide = getHide(root.left); if(leftHide == -1) return -1; int rightHide = getHide(root.right); if (rightHide == -1) return -1; int result = 1; if(Math.abs(leftHide - rightHide) > 1){ return -1; } else{ result += getMax(leftHide , rightHide); return result ; } } public boolean isBalanced(TreeNode root) { return (getHide(root) != -1) ; } }
LeetCode257.二叉树的所有路径
class Solution { public List<String> binaryTreePaths(TreeNode root) { List<String> res = new ArrayList<>(); if(root == null){ return res; } List<Integer> path = new ArrayList<>(); traversal(root , path , res); return res; } public void traversal(TreeNode root , List<Integer> path , List<String> res){ path.add(root.val); if(root.left==null && root.right==null){ StringBuilder sb = new StringBuilder(); for(int i = 0; i < path.size() - 1; i++){ sb.append(path.get(i)).append("->"); } sb.append(path.get(path.size() - 1)); res.add(sb.toString()); return; } if(root.left != null){ traversal(root.left , path , res); path.remove(path.size() - 1); } if(root.right != null){ traversal(root.right , path , res); path.remove(path.size() - 1); } } }
LeetCode404.左叶子之和
class Solution { public int sumOfLeftLeaves(TreeNode root) { if(root == null){ return 0; } int leftnum = sumOfLeftLeaves(root.left); int rightnum = sumOfLeftLeaves(root.right); // if(root.left == null){ // return; // } int num = 0; if(root.left != null && root.left.left == null && root.left.right == null){ num = root.left.val; //return num; 这里不能直接return,如果遇到左子叶就在第二层的时候,这时候这里就会return了,那么整个二叉树遍历也就结束了,后续其他节点会直接无法遍历得到 } int sum = num + leftnum + rightnum; return sum; } }