题目:110. 平衡二叉树 - 力扣(LeetCode)
思路/想法:
遍历顺序:后序遍历。
代码实现:
// 递归法
class Solution {
public boolean isBalanced(TreeNode root) {
return getHeight(root) != -1;
}
private int getHeight(TreeNode root) {
if (root == null) {
return 0;
}
int leftHeight = getHeight(root.left);
if (leftHeight == -1) return -1;
int rightHeight = getHeight(root.right);
if (rightHeight == -1) return -1;
if (Math.abs(leftHeight - rightHeight) > 1) return -1;
return Math.max(leftHeight, rightHeight) + 1;
}
}
//
题目:257. 二叉树的所有路径 - 力扣(LeetCode)
思路/想法:
前序遍历
代码实现:
class Solution {
List<String> ans = new ArrarList<>();
public List<String> binaryTreePaths(TreeNode root) {
deal(root, ""); // 调用递归方法,初始路径为空字符串
return ans; // 返回结果集合
}
void deal(TreeNode node, String s) { // 定义递归方法,参数为当前节点和当前路径
if (root == null) return; // 如果当前节点为空,直接返回
if (node.left == null && node.right == null) { // 如果当前节点为叶子节点
ans.add(new StringBuilder(s).append(node.val).toString()); // 将当路径加上当前节点的值,添加到结果集合中
return; // 返回
}
String temp = new StringBuilder(s).append(node.val).append("->").toString(); // 将当前节点的值加上"->",得到新的路径
deal(node.left, temp); // 递归处理左子树,传入新的路径
deal(node.right, temp); // 递归处理右子树,传入新的路径
}
}
// 迭代法
class Solution {
public List<String> binaryTreePaths(TreeNode root) {
List<String> ans = new ArrayList<>();
if (root == null) return ans;
Stack<Object> stack = new Stack<>();
// 节点和节点值都加入栈中
stack.push(root);
stack.push(root.val + "");
while (!stack.isEmpty()) {
String s = (String) stack.pop();
TreeNode node = (TreeNode) stack.pop();
// 叶子节点则输出结果
if (node.left == null && node.right == null) {
ans.add(s);
}
// 左孩子节点不为空
if (node.left != null) {
stack.push(node.left);
stack.push(s + "->" + node.left.val);
}
// 右孩子节点不为空
if (node.right != null) {
stack.push(node.right);
stack.push(s + "->" + node.right.val);
}
}
return ans;
}
}
题目:404. 左叶子之和 - 力扣(LeetCode)
思路/想法:
前序遍历
代码实现:
class Solution {
public int sumOfLeftLeaves(TreeNode root) {
// 左叶子之和:上一个节点的左子树不为空且当前节点的左右子树为空
if (root == null) return 0;
int leftValue = sumOfLeftLeaves(root.left);
int rightValue = sumOfLeftLeaves(root.right);
int midValue = 0;
if (root.left != null && root.left.left == null && root.left.right == null) {
midValue = root.left.val;
}
int sum = midValue + leftValue + rightValue;
return sum;
}
}