算法 分治法 二叉树深度

来源:互联网 发布:竞价软件有用吗 编辑:程序博客网 时间:2024/06/08 09:40
public class Test2 {    static TreeNode<Integer> t1;    static int leftDepth = 1;    static int rightDepth = 1;    public static void main(final String[] args) throws Exception {        initData();        int depth = caculateDepth(t1);        System.out.println(depth+"");    }    private static void initData() {        //1.        t1 = new TreeNode<>(154);        //2.父 左        t1.addLeft(254);        //父 左 左, 父 左 右        t1.leftChild.addLeft(97);        t1.leftChild.addRight(101);        //父 左 右 左        t1.leftChild.rightChild.addLeft(66);        //父 左 右 左 左, 父 左 右 左 右        t1.leftChild.rightChild.leftChild.addLeft(33);        t1.leftChild.rightChild.leftChild.addRight(100);        //3.父 右        t1.addRight(354);        //父 右 左        t1.rightChild.addLeft(88);    }    private static int caculateDepth(TreeNode t) {        int depth = 0;        if (t != null) {            int leftDepth = caculateDepth(t.leftChild);            int rightDepth = caculateDepth(t.rightChild);            //从第一个解析,左边最大长度和右边最大长度,肯定取更长的+1            depth = leftDepth >= rightDepth ? leftDepth + 1 : rightDepth + 1;        }        return depth;    }}class TreeNode<T> {    T value;    TreeNode<T> leftChild;    TreeNode<T> rightChild;    TreeNode(T value) {        this.value = value;    }    TreeNode() {    }    public void addLeft(T value){        TreeNode<T> leftChild = new TreeNode<T>(value);        this.leftChild = leftChild;    }    public void addRight(T value){        TreeNode<T> rightChild = new TreeNode<T>(value);        this.rightChild = rightChild;    }    @Override    public boolean equals(Object obj) {        // TODO Auto-generated method stub        if(!(obj instanceof TreeNode)){            return false;        }        return this.value.equals(((TreeNode<?>)obj).value);    }    @Override    public int hashCode() {        // TODO Auto-generated method stub        return this.value.hashCode();    }    @Override    public String toString(){        return this.value==null?"":this.value.toString();    }

}

时间复杂度:因为每个节点都只遍历了一次,所以是O(N)