Easy understand c++ using DFS


  • -1
    T
    class Solution {
    public:
        void dfs(TreeNode* root, double target, int &val)
        {
            val = fabs(val - target) < fabs(root->val - target) ? val : root->val;
            if(root->left)
            {
                dfs(root->left, target, val);
            }
            
            if(root->right)
            {
                dfs(root->right, target, val);
            }
        }
    
        int closestValue(TreeNode* root, double target) {
            
            //special case
            if(root->left == nullptr && root->right == nullptr)
            {
                return root->val;
            }
            
            int val = INT_MAX;
            dfs(root, target, val);
            return val;
        }
    };

  • 0
    C

    If you check if(root->left) and if(root->right), it means you did not make use of the properties of binary search tree, this method works for normal binary tree.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.