leetcode-完全二叉树节点个数

给定一颗完全二叉树,求节点个数:
https://leetcode-cn.com/problems/count-complete-tree-nodes/

简单粗暴的递归

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int countNodes(TreeNode root) {
        if(root==null){
            return 0;
        }
        return countNodes(root.left)+countNodes(root.right)+1;
    }
}

具体情况具体分析

根据完全二叉树的特点,给每个节点编号,根节点是1,左孩子是2,右孩子是3 。。。那么【最下最右】的叶节点的编号就是总节点个数。先遍历左节点计算出树的高度h,然后再按先右子树深度优先遍历,给节点上编号,直到深度为h是,节点编号pos即是树节点总数。

class Solution {
    //树高度
    private int depth=0;

    public int countNodes(TreeNode root) {
        if(root==null){
            return 0;
        }
        //计算树的高度
        TreeNode p = root;
        while(p!=null){
            depth++;
            p=p.left;
        }

        //深度优先遍历,先右子树,给节点编号,根节点是1,右孩子是2*i+1,左孩子2*i
        //最右最下的叶节点高度一定是h。
        return dfs(root,1,1); 
    }

    private int dfs(TreeNode root,int currDepth,int pos){
        if(root==null){
            return 0;
        }
        //高度到了depth,返回
        if(depth==currDepth){
            return pos;
        }
        //先计算右子树
        int right=dfs(root.right,currDepth+1,(pos<<1)+1); 
        return right>0?right:dfs(root.left,currDepth+1,(pos<<1)); 
    }

}
原文地址:https://www.cnblogs.com/teacherma/p/14028533.html