public boolean isSameTree(TreeNode p, TreeNode q) {
return preNode(p, q);
}
public boolean preNode(TreeNode p, TreeNode q) {
if (p == null && q == null) {
return true;
}
if (p == null || q == null) {
return false;
}
if (p!=null && q!=null && p.val != q.val) {
return false;
}
return preNode(p.left, q.left) && preNode(p.right, q.right);
}
// 对称二叉树
public boolean isSymmetric(TreeNode root) {
if (root == null) {
return true;
}
Boolean b = preNode(root.left, root.right);
return b;
}
Boolean preNode(TreeNode left, TreeNode right) {
if (left == null && right == null) {
return true;
}
if (left == null || right == null) {
return false;
}
if (left.val != right.val) {
return false;
}
return preNode(left.left, right.right) && preNode(left.right, right.left);
}
// 合并到root1上
public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
if (root1 == null) {
return root2;
}
if (root2 == null) {
return root1;
}
TreeNode merge = new TreeNode(root1.val + root2.val);
merge.left = mergeTrees(root1.left, root2.left);
merge.right = mergeTrees(root1.right, root2.right);
return merge;
}
LeetCode257:给你一个二叉树的根节点 root ,按 任意顺序 ,返回所有从根节点到叶子节点的路径。
叶子节点是指没有子节点的节点。
public List<String> binaryTreePaths(TreeNode root) {
final ArrayList<String> result = new ArrayList<>();
dfs(root, "", result);
return result;
}
void dfs(TreeNode root, String path, List<String> res) {
if (root==null){
return;
}
path += root.val;
if (root.left != null || root.right != null) {
path += "->";
}
if (root!=null && root.left == null && root.right==null) {
res.add(path);
}
dfs(root.left, path, res);
dfs(root.right, path, res);
}
上面我们讨论的找所有路径的方法,那我们是否可以再找一下哪条路径的和为目标值呢?这就是LeetCode112题:给你二叉树的根节点 root 和一个表示目标和的整数 targetSum ,判断该树中是否存在 根节点到叶子节点 的路径,这条路径上所有节点值相加等于目标和 targetSum。叶子节点 是指没有子节点的节点。
public boolean hasPathSum(TreeNode root, int targetSum) {
final ArrayList<Integer> result = new ArrayList<>();
dfs(root, 0, result);
if (result.contains(targetSum)) {
return true;
}
return false;
}
void dfs(TreeNode root, int currentSum, List<Integer> result) {
if (root == null) {
return;
}
currentSum += root.val;
if (root.left == null && root.right == null) {
result.add(currentSum);
}
dfs(root.left, currentSum, result);
dfs(root.right, currentSum, result);
}
public boolean hasPathSum(TreeNode root, int targetSum) {
if (root == null) {
return false;
}
if (root.left == null && root.right == null) {
return root.val == targetSum;
}
boolean left = hasPathSum(root.left, targetSum - root.val);
boolean right = hasPathSum(root.right, targetSum - root.val);
return left || right;
}
public TreeNode invertTree(TreeNode root) {
if (root == null) {
return null;
}
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
invertTree(root.left);
invertTree(root.right);
return root;
}