代码随想录训练营第17天|110.平衡二叉树,257. 二叉树的所有路径,404.左叶子之和
)
110.平衡二叉树
文章
思路
递归,如果左右子树都是平衡二叉树则本节点高度为左右子树深度较大者+1
如果左右子树中有一棵不是平衡二叉树,则本节点为根的树不是平衡二叉树。
难点在如何同时传递两个子树的深度和是不是平衡二叉树的信息。
代码
class Solution {
public boolean isBalanced(TreeNode root) {
return getHeight(root) != -1;
}
public int getHeight(TreeNode root) {
if (root == null) {
return 0;
}
int lh = getHeight(root.left);
int rh = getHeight(root.right);
if (Math.abs(lh - rh) > 1) {
return -1;
}
if (lh == -1 || rh == -1) {
return -1;
}
return (lh > rh ? lh : rh) + 1;
}
}
257. 二叉树的所有路径
文章
思路
dfs,动态记录路径
代码
class Solution {
private ArrayList<Integer> order = new ArrayList<>();
private List<String> res = new ArrayList<>();
public List<String> binaryTreePaths(TreeNode root) {
dfs(root);
return res;
}
public void dfs(TreeNode root) {
order.add(root.val);
if (root.left == null && root.right == null) {
res.add(convert(order));
}
if (root.left != null)
dfs(root.left);
if (root.right != null)
dfs(root.right);
order.remove(order.size() - 1);
}
public String convert(ArrayList<Integer> list) {
StringBuilder sb = new StringBuilder();
int i, n;
n = list.size();
sb.append(list.get(0).toString());
for (i = 1; i < n; ++i) {
sb.append("->" + list.get(i));
}
return sb.toString();
}
}
404. 左叶子之和
文章
思路
遍历所有非空的非叶子节点,如果其左孩子节点为叶子节点则求和
代码
class Solution {
public int sumOfLeftLeaves(TreeNode root) {
int res = 0;
Stack<TreeNode> st = new Stack<>();
if (root != null && !checkLeaf(root)) {
st.push(root);
}
TreeNode node;
while (!st.isEmpty()) {
node = st.pop();
if (node.left != null && !checkLeaf(node.left)) {
st.push(node.left);
} else if (node.left != null) {
res += node.left.val;
}
if (node.right != null && !checkLeaf(node.right)) {
st.push(node.right);
}
}
return res;
}
public boolean checkLeaf(TreeNode node) {
return node.left == null && node.right == null;
}
}
总结
递归方法不太好想了