二叉树其他操作

二叉树的镜像

剑指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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值