二叉树的镜像
剑指offer19
1 1
/ \ / \
2 3 --> 3 2
/ \
4 4
//若返回一个新的独立的树
public TreeNode getIso(TreeNode root){
if(root == null) return null;
TreeNode nRoot = new TreeNode(root.val);
nRoot.left = getIso(root.right);
nRoot.right = getIso(root.left);
return nRoot;
}
----------
//若在原树上更改
public TreeNode getIso(TreeNode root){
if(root == null) return null;
TreeNode tn = root.left;
root.left = root.right;
root.right = tn;
getIso(root.left);
getIso(root.right);
return root;
}
节点的最近公共祖先
思路:有很多思路,首先直观的是打印两条从根到节点的路径从头查找最远相同的节点;递归判断节点是否左子树包含一个节点并且右子树包含一个节点,当符合时返回【具体代码较难想】。
此处练习第二种递归方式:
将两条链路保存下来再找两条链路第一个不同的节点即可
public TreeNode getNearestFarther(TreeNode root, TreeNode fir, TreeNode sec){
if(root == null || fir == null || sec == null) return null;
List<TreeNode> ls1 = new ArrayList<TreeNode>(), ls2 = new ArrayList<TreeNode>(), ls = new ArrayList<TreeNode>();
getPath(root, fir, ls, ls1);
getPath(root, sec, ls, ls2);
int i = 0;
for(; i < ls1.size() && i < ls2.size(); i++){
if(ls1.get(i) != ls2.get(i)) break;
}
return ls1.get(i-1);
}
public void getPath(TreeNode root, TreeNode node, List<TreeNode> ls, List<TreeNode> rs){
if(root == null) return;
ls.add(root);
if(root == node) for(int i = 0; i < ls.size(); i++) rs.add(ls.get(i));
getPath(root.left, node, ls, rs);
getPath(root.right, node, ls, rs);
ls.remove(ls.size()-1);
}
求二叉树中相距最远的两个节点的距离(与求二叉树PathSum中加和最大类似)
public int furdis;
public int furthest(TreeNode root){
furdis = Integer.MIN_VALUE;
getFur(root);
return furdis;
}
public int getFur(TreeNode root){
if(root == null) return 0;
int left = getFur(root.left);
int right = getFur(root.right);
furdis = furdis > left+right+1 ? furdis : left+right+1;
return left > right ? left+1 : right+1;
}