求二叉樹葉子節點的個數


tag: 二叉樹

 

思路:

(1)通過先序遍歷的方式求解

(2)葉子節點的特點: 左右孩子都為空

 

也可以用遞歸方式

 

package com.zhaochao.tree;

import java.util.Stack;

/**
 * Created by zhaochao on 17/1/23.
 * 葉子結點的特點: 左右孩子都為空
 * 通過先序的方式找到葉子結點
 *
 */
public class LeafNumber {

    int flag = 0;

    public int getCountsOfLeaves(TreeNode root) {
        int count = 0;
        if(root == null) {
            return count;
        }
        Stack<TreeNode> stack = new Stack<TreeNode>();
        stack.push(root);
        while(!stack.isEmpty()) {
            TreeNode node = stack.pop();
            if(node.left == null && node.right == null) {
                count++;
            }
            if(node.right != null) {
                stack.push(node.right);
            }
            if(node.left != null) {
                stack.push(node.left);
            }
        }
        return count;
    }

    //遞歸求解
    public void getCountRec(TreeNode root) {
        if(root == null) {
            return;
        }
        if(root.left == null && root.right == null) {
            flag++;
        }
        getCountRec(root.left);
        getCountRec(root.right);
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(0);
        TreeNode node1 = new TreeNode(1);
        TreeNode node2 = new TreeNode(2);
        TreeNode node3 = new TreeNode(3);
        TreeNode node4 = new TreeNode(4);

        root.left = node1;
        root.right = node2;
        node2.left = node3;
        node2.right = node4;

        LeafNumber test = new LeafNumber();
        int count = 0;
        count = test.getCountsOfLeaves(root);

        System.out.println("The number of nodes in the tree is " + count);

        test.getCountRec(root);
        System.out.println("Recursion : the number of nodes in the tree is " + test.flag);


    }


}

  

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM