114. 二叉树展开为链表
给定一个二叉树,原地将它展开为一个单链表。
例如,给定二叉树
将其展开为:
题解:
把右子树放到左子树最后一个人节点的右子树中
左子树置空
solution:
class Solution {
public void flatten(TreeNode root) {
if (root == null) return;
if (root.left != null) {
TreeNode last = root.left;
while (last.right != null) last = last.right; // 找到左子树最后一个节点
// 子树的移动
last.right = root.right;
root.right = root.left;
root.left = null;//左子树置空
}
flatten(root.left);
flatten(root.right);
}
}
116. 填充每个节点的下一个右侧节点指针
给定一个完美二叉树,其所有叶子节点都在同一层,每个父节点都有两个子节点。二叉树定义如下:
struct Node {
int val;
Node *left;
Node *right;
Node *next;
}
填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为 NULL。
初始状态下,所有 next 指针都被设置为 NULL。
题解:
1)当不是同一个父节点时需要注意操作
solution:
class Solution {
public Node connect(Node root) {
if(root==null) return null;
ConnectTwoNode(root.left,root.right);
return root;
}
void ConnectTwoNode(Node node1,Node node2){
if(node1==null||node2==null) return;
node1.next=node2;
ConnectTwoNode(node1.left,node1.right);
ConnectTwoNode(node2.left,node2.right);
ConnectTwoNode(node1.right,node2.left);
}
}
530. 二叉搜索树的最小绝对差
给你一棵所有节点为非负值的二叉搜索树,请你计算树中任意两节点的差的绝对值的最小值。
示例:
输入:
1
3
/
2
输出:
1
解释:
最小绝对差为 1,其中 2 和 1 的差的绝对值为 1(或者 2 和 3)。
```java
class Solution {
private int pre;
private int ans;
public int getMinimumDifference(TreeNode root) {
pre=-1;
ans= Integer.MAX_VALUE;
inorder(root);
return ans;
}
void inorder(TreeNode root){
if(root==null) return;
inorder(root.left);
if(pre!=-1)
ans=Math.min(ans,root.val-pre);
pre=root.val;
inorder(root.right);
}
}