二叉树节点间的最大距离问题

来源:互联网 发布:商家给淘宝消费积分 编辑:程序博客网 时间:2024/06/06 17:40
/** * Created by lxw, liwei4939@126.com on 2017/10/30. * 二叉树节点间的最大距离问题 */public class BTMaxDistance {    public class Node{        int value;        Node left;        Node right;        public Node(int data){            this.value = data;        }    }        public int MaxDistance(Node head){        int[] record = new int[1];        return posOrder(head, record);    }        public int posOrder(Node head, int[] record){        if(head == null){            record[0] = 0;            return 0;        }        int lMax = posOrder(head.left, record);        int MaxfromLeft = record[0];        int rMax = posOrder(head.right, record);        int MaxfromRight = record[0];        record[0] = Math.max(MaxfromLeft, MaxfromRight) + 1;        int curNodeMax = MaxfromLeft + MaxfromRight + 1;        return Math.max(Math.max(lMax, rMax), curNodeMax);    }}

原创粉丝点击