2018-04-18 二叉树取最大节点

在二叉树中寻找值最大的节点

给出如下一棵二叉树:


 
            a(1) 
           /      \
        b(-5)      c(2)
        /   \      /   \
     d(0) e(3)  f(-4)  g(-5) 
                   \
                   h(6)
                  /
                m(4)
     
     
返回值为 6 的节点。

代码如下:

package cn.jq.binarytree;

import java.util.ArrayList;

import cn.jq.binarytree.BinaryTree.Node;

public class SortBinaryTree {

    
    /**
     * 创建一颗整型二叉树, 
     *       a(1) 
     *     /      \
     *  b(-5)      c(2)
     *  /   \      /   \
     *d(0) e(3)  f(-4)  g(-5) 
     *              \
     *              h(6)
     *             /
     *           m(4)
     * @return
     */
    public static BinaryTree initBinaryTree() {
        Node m = new BinaryTree().new Node("4", null, null);
        Node h = new BinaryTree().new Node("6", m, null);
        Node g = new BinaryTree().new Node("-5", null, null);
        Node f = new BinaryTree().new Node("-4", null, h);
        Node e = new BinaryTree().new Node("3", null, null);
        Node d = new BinaryTree().new Node("0", null, null);
        Node c = new BinaryTree().new Node("2", f, g);
        Node b = new BinaryTree().new Node("-5", d, e);
        Node a = new BinaryTree().new Node("1", b, c);
        Node root = a; 
        return new BinaryTree(root);
    }
    
    public Node maxNode(Node root) {
        //Write your code here
        ArrayList<Node> result = new ArrayList<Node>();
        result.add(root);
        search(root, result);
        return result.get(0);
    }
    
    
    //递归查询最大节点
    public void search(Node root, ArrayList<Node> result) {
        if (root == null) {
            return ;
        }
        if (Integer.valueOf(result.get(0).getData()) < Integer.valueOf(root.getData())) {
            result.set(0, root);
        }
        if (root.getLchild() != null) {
            search(root.getLchild(), result);
        }
        if (root.getRchild() != null) {
            search(root.getRchild(), result);
        }
    }
    
    
    public static void main(String args[]) {
        BinaryTree tree = SortBinaryTree.initBinaryTree();
        SortBinaryTree sortBinary = new SortBinaryTree();
        System.out.println(sortBinary.maxNode(tree.getRoot()).getData());
    }
}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 树的概述 树是一种非常常用的数据结构,树与前面介绍的线性表,栈,队列等线性结构不同,树是一种非线性结构 1.树的定...
    Jack921阅读 4,509评论 1 31
  • 如需转载, 请咨询作者, 并且注明出处.有任何问题, 可以关注我的微博: coderwhy, 或者添加我的微信: ...
    coderwhy阅读 9,003评论 12 35
  • 一直以来,我都很少使用也避免使用到树和图,总觉得它们神秘而又复杂,但是树在一些运算和查找中也不可避免的要使用到,那...
    24K男阅读 6,786评论 5 14
  • 题量有点多,建议Ctrl + F题号或题目哦~ 二叉树的遍历(前序遍历,中序遍历,后序遍历)[144] Binar...
    野狗子嗷嗷嗷阅读 9,164评论 2 37
  • 世界上有很多需要说不的地方,可是有一些人并不是那么的喜欢,说不,在上课的时候,班长喊了起立,但是仍然有一些人在那块...
    李jing源阅读 565评论 1 0