最近在看一些算法相关的东西其中就有一个二叉树的主题内容 这篇文章就是记录下我看到的 有很多的不足的地方和理解不到的地方 希望大家可以一起来讨论下
首先一棵树要么是空树, 要么有两个指针 每一个指针指向一个树. 树是一种递归结构 所以很多树的问题都可以使用递归来处理
树的高度
- 给定一个二叉树 求该树的高度
- 这个题的解法就是使用递归顶层遍历有一个节点就加一然后比较出左右高度最高的
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
return Math.max(maxDepth(root.lefr), maxDepth(root.right)) + 1;
}
平衡树
- 平衡树就是树的左右子树的高度差小于等于1
- 如果是一个平衡树 那么他的子树也必然是平衡树 所以在计算高度的同时 查看子树是否是平衡树 如果有一个不是那么该树 就不是平衡树
private boolean result = true;
public boolean isBalanced(TreeNode root) {
maxDepth(root);
return result;
}
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
int l = maxDepth(root.left);
int r = maxDepth(root.right);
if (Max.abs(l - r) > 1) {
result = false;
}
return Math.max(l, r) + 1;
}
两节点的最长路径
private int max = 0;
public int diameterOfBinaryTree(TreeNode root) {
}
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
int l = maxDepth(root.left);
int r = maxDepth(root.right);
max = Math.max(max, l + r);
return Math.max(l, r) + 1;
}
翻转树
public TreeNode invertTree(TreeNode root) {
if (root == null) {
retrun null;
}
TreeNode left = root.left;
root.left = invertTree(root.right);
root.right = invertTree(left);
return root;
}
归并两棵树
public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
if (t1 == nill && t2 == null) {
return null;
}
if (t1 == null) {
return t2;
}
if (t2 == null) {
return t1;
}
TreeNode root = new TreeNode(t1.val + t2.val);
root.left = mergeTrees(t1.left, t2.left);
root.right = mergeTrees(t1.right, t2.right);
return root;
}