剑指OFFER第八题 二叉树的下一节点

leetcode没有这个题目,自己写了一个测试程序
含自己的解决算法

import java.util.List;
import java.util.Random;

public class TreeNextNodeTest {
    public static void main(String[] args) {
        //根据前中后序生成树
        MyTree root = MyTree.getTreeWithPostMid("DCBHKGFEA".toCharArray(),
                "BDCAEHGKF".toCharArray());

        MyTree sample = getTestSample(root);
        System.out.println("Your method: " + solve(sample));
        System.out.println("Correct Answer: " + getAns(sample));
        System.out.println("Current Node Value" + sample.getVal());
        System.out.println(root.getTraversal(TraversalMethod.MID));
    }


    //随机数获取测试数据
    private static MyTree getTestSample(MyTree root){
        int depth = root.getDepth();

        Random random = new Random(System.currentTimeMillis());

        int randomDepth = random.nextInt(depth);
        MyTree ans = root;
        while (ans != null && randomDepth > 0){
            randomDepth--;
            int swt = random.nextInt(10)/5;

            if (swt == 0 && ans.getLeft() != null){
                ans = ans.getLeft();
            } else if (ans.getRight() != null) {
                ans = ans.getRight();
            }

        }

        return ans;
    }

    //获取正确答案
    private static Character getAns(MyTree current){
        MyTree father = current;
        while (father.getFather() != null){
            father = father.getFather();
        }
        List<Character> list = father.getTraversal(TraversalMethod.MID);

        try{
            Character c = new Character(list.get(list.indexOf(current.getVal()) + 1 ));
            return c;
        } catch (Exception e){

        }

        return null;
    }

    //自己的方法
    public static Character solve(MyTree current){

        if (current.getRight() != null){
            return getTheLeft(current.getRight());
        } else if (current == current.getFather().getLeft()){
            return current.getFather().getVal();
        } else {
            MyTree child = current;
            MyTree father = current.getFather();
            while (father != null && child != father.getLeft()){
                child = father;
                father = child.getFather();
            }

            return (father == null) ? null : father.getVal();
        }

    }

    private static Character getTheLeft(MyTree current){
        MyTree ans = current;

        while (ans.getLeft() != null){
            ans = ans.getLeft();
        }

        return ans.getVal();
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值