二叉树的节点(java)

public int getAns(TreeNode root) {
       // write your code here
        HashMap map = new HashMap();
        map.put("max",1);
        if(root == null) {
            return 0;
        }
        findMax(root,map);
        return (int)map.get("max");
    }
    public void findMax(TreeNode root,HashMap map){
        //代表已到叶子节点
        if(root.left == null&& root.right == null) {
            /*int target = (int)map.get("max");
                target++;
                map.put("max",target);*/
                return;
        }
        if(root.left != null){
            map.put("max",(int)map.get("max")+1);
            findMax(root.left,map);
        }
        if(root.right != null){
            map.put("max",(int)map.get("max")+1);
            findMax(root.right,map);
        }
    }

 

Java 中,可以使用一个 Node 类来表示二叉树的结,并使用一个 BinaryTree 类来表示整个二叉树。以下是一个简单的示例代码,演示如何添加一个新的结二叉树中: ``` // Node 类表示二叉树的结 class Node { int data; // 结的数据 Node left, right; // 左子结和右子结 public Node(int data) { this.data = data; left = right = null; } } // BinaryTree 类表示整个二叉树 class BinaryTree { Node root; // 根结 public BinaryTree() { root = null; } // 添加一个新的结二叉树中 public void add(int data) { Node newNode = new Node(data); // 创建新的结 if (root == null) { // 如果根结为空,则把新结作为根结 root = newNode; return; } Node current = root; Node parent = null; while (true) { parent = current; if (data < current.data) { // 如果新结的值比当前结小,向左遍历 current = current.left; if (current == null) { // 如果左子结为空,就把新结插入到左子结的位置 parent.left = newNode; return; } } else { // 如果新结的值比当前结大,向右遍历 current = current.right; if (current == null) { // 如果右子结为空,就把新结插入到右子结的位置 parent.right = newNode; return; } } } } } ``` 在上面的代码中,add() 方法接收一个整数作为参数,表示要添加的新结的值。首先,它创建一个新的结,然后根据二叉树的性质,将新结插入到二叉树中的合适位置。如果二叉树为空,就把新结作为根结。如果二叉树不为空,就从根结开始遍历二叉树,向左或向右遍历,直到找到一个空结,然后把新结插入到这个空结的位置。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值