二叉搜索树
参考:二叉搜索树相关题目
树的最近公共祖先
参考:树的最近公共祖先问题
二叉树层次遍历
参考:二叉树层次遍历
二叉树前序、中序、后序遍历(递归迭代六种写法)
重建二叉树
二叉树路径和
参考:二叉树路径和相关题目
《剑指offer》相关题目
LeetCode
class Solution {
public Node connect(Node root) {
if(root==null){
return null;
}
connectTwoNode(root.left, root.right);
return root;
}
public void connectTwoNode(Node left, Node right) {
if (left == null || right == null) {
return;
}
left.next = right;
connectTwoNode(left.left, left.right);
connectTwoNode(right.left, right.right);
connectTwoNode(left.right, right.left);
}
}
反转二叉树
226. 翻转二叉树
class Solution {
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;
}
}
二叉树展开为链表
114. 二叉树展开为链表
class Solution {
public void flatten(TreeNode root) {
if (root==null) {
return;
}
flatten(root.left);
flatten(root.right);
TreeNode left = root.left;
TreeNode right = root.right;
root.left = null;
root.right = left;
TreeNode p = root;
while (p.right != null) {
p = p.right;
}
p.right = right;
}
}
二叉树的直径
class Solution {
//需要一个辅助参数
private int result = 1;
public int diameterOfBinaryTree(TreeNode root) {
depth(root);
return result - 1;
}
public int depth(TreeNode root){
if(root == null){
return 0;
}
int left = depth(root.left);
int right = depth(root.right);
result = Math.max(result, left + right + 1);
return 1 + Math.max(left, right);
}
}
二叉树最大宽度
题目链接:662. 二叉树最大宽度
class Solution {
private int result;
//key是深度,value这一层第一个位置
private Map<Integer, Integer> map;
public int widthOfBinaryTree(TreeNode root) {
result = 0;
map = new HashMap<>();
dfs(root, 0, 0);
return result;
}
//前序遍历
public void dfs(TreeNode root, int depth, int position) {
if (root == null) {
return;
}
if (map.get(depth) == null) {
map.put(depth, position);
}
result = Math.max(result, position - map.get(depth) + 1);
dfs(root.left, depth + 1, 2 * position);
dfs(root.right, depth + 1, 2 * position + 1);
}
}
二叉树的右视图
二叉树的完全校验
题目链接:958. 二叉树的完全性检验
class Solution {
public boolean isCompleteTree(TreeNode root) {
Queue<TreeNode> q = new LinkedList<>();
q.offer(root);
boolean reachedEnd = false;
while(!q.isEmpty()){
TreeNode cur = q.poll();
if(reachedEnd && cur != null){
return false;
}
if(cur == null){
reachedEnd = true;
continue;
}
q.offer(cur.left);
q.offer(cur.right);
}
return true;
}
}
判断两棵二叉树是否相同
题目链接:100. 相同的树
class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
if (p == null && q == null) {
return true;
}
if (p != null && q != null && p.val == q.val) {
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}
return false;
}
}
合并二叉树
题目链接:617. 合并二叉树
class Solution {
public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
if (t1 == null) {
return t2;
}
if (t2 == null) {
return t1;
}
t1.val += t2.val;
t1.left = mergeTrees(t1.left, t2.left);
t1.right = mergeTrees(t1.right, t2.right);
return t1;
}
}