本题思路:利用前序遍历的思想。用递归来解决。
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> res = new LinkedList();
if(root == null){
return res;
}
List<Integer> paths = new LinkedList();
travel(root,paths,res);
return res;
}
public void travel(TreeNode root, List<Integer> paths, List<String> res){
// 先把根节点放入Paths中
paths.add(root.val);
if(root.left == null && root.right == null){
StringBuilder sb = new StringBuilder();
for(int i = 0; i < paths.size() - 1; i++){
sb.append(paths.get(i) + "->");
}
sb.append(paths.get(paths.size() - 1));
res.add(sb.toString());
return;
}
if(root.left != null){
travel(root.left,paths,res);
paths.remove(paths.size()-1);
}
if(root.right != null){
travel(root.right,paths,res);
paths.remove(paths.size()-1);
}
}
}
本题思路: 递归思想。
class Solution {
public boolean isBalanced(TreeNode root) {
if(root == null){
return true;
}
int l = height(root.left);
int r = height(root.right);
boolean res = Math.abs(l-r)<=1?true:false;
boolean left = isBalanced(root.left);
boolean right = isBalanced(root.right);
return res && left && right;
}
public int height(TreeNode root){
if(root == null){
return 0;
}
int left = height(root.left);
int right = height(root.right);
return Math.max(left,right) + 1;
}
}
本题思路: 递归思想
class Solution {
public int sumOfLeftLeaves(TreeNode root) {
if(root == null){
return 0;
}
// 用来记录当前节点的直接左叶子节点的值
int res = (root.left != null && root.left.left == null && root.left.right == null) == true?root.left.val:0;
int l = sumOfLeftLeaves(root.left);
int r = sumOfLeftLeaves(root.right);
return l + r + res;
}
}