Algorithms—222.Count Complete Tree Nodes

来源:互联网 发布:中国书画网络展览馆 编辑:程序博客网 时间:2024/06/06 08:36

思路:利用完全二叉树的对称性质,左右分别探索长度,如果相同,直接返回2^h-1,否则分别计算左树和右树

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public int countNodes(TreeNode root) {    if (root==null) {return 0;}        int l=getLeft(root);        int r=getRight(root);        if (l==r) {return (2<<(l-1)) - 1;  }        return 1+countNodes(root.left) + countNodes(root.right) ;      }    public int getLeft(TreeNode root){    int h=0;    while(root!=null){        h++;        root=root.left;    }    return h;    }    public int getRight(TreeNode root){        int h=0;    while(root!=null){        h++;        root=root.right;    }    return h;    }}


0 0