Count Good Nodes in Binary Tree

Given a binary tree root, a node X in the tree is named good if in the path from the root to X there are no nodes with a value greater than X.

Find the number of good nodes in the binary tree.
Example 1:
Input: root = {3,3,null,4,2}
Output: 3

Approach

Java


public class CountGoodNodesInBinaryTree {
    public static void main(String[] args) {
        TreeNode root = new TreeNode(3);
        root.left = new TreeNode(3);
        root.left.left = new TreeNode(4);
        root.left.right = new TreeNode(2);
        System.out.println(goodNodes(root));
    }

    static int dfs(TreeNode rootint max1) {
        if (root == null)
            return 0;
        int cnt = 0;
        if (root.val >= max1) {
            max1 = root.val;
            cnt++;
        }
        int leftAns = dfs(root.left, max1);
        int rightAns = dfs(root.right, max1);
        return leftAns + rightAns + cnt;
    }

    static int goodNodes(TreeNode root) {
        if (root == null)
            return 0;
        return dfs(root, Integer.MIN_VALUE);
    }
}

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode() {
    }

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int valTreeNode leftTreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

C++

#include <bits/stdc++.h>
using namespace std;
//struct for treenode
struct TreeNode{
    int data;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int data)
    {
        this->data=data;
        this->left=NULL;
        this->right=NULL;
    }
}; 

int dfs(TreeNode *root,int max1)
{
        if(root==NULL)
              return 0;
        int cnt=0;
        if(root->data>=max1)
        {
            max1=root->data;
            cnt++;
        }
        int leftAns=dfs(root->left,max1);
        int rightAns=dfs(root->right,max1);
        return leftAns+rightAns+cnt;
}
int goodNodes(TreeNode* root
{
      if(root==NULL)
            return 0;
      return dfs(root,INT_MIN);
}


int main()
{
    TreeNode *root=new TreeNode(3);
    root->left=new TreeNode(3);
    root->left->left=new TreeNode(4);
    root->left->right=new TreeNode(2);
    cout<<goodNodes(root);
    return 0
}


No comments:

Post a Comment