C++ DFS recursion with simple explanation


  • 0

    The next level nodes do work only if root->val==root->left->val or root->val==root->right->val.

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        int findSecondMinimumValue(TreeNode* root) {
            int result = -1;
            if (!root || (!root->left && !root->right)) return result;
            int a = root->val, b = -1, c = -1;
            if (root->left) {
                int left = findSecondMinimumValue(root->left);
                b = root->left->val == a ? (left == -1 ? a : left) : root->left->val;
            }
            if (root->right) {
                int right = findSecondMinimumValue(root->right);
                c = root->right->val == a ? (right == -1 ? a : right) : root->right->val;
            }
            if (b < c) {
                if (b > a) result = b;
                else result = c;
            } else if (b == c) {
                if (b > a) result = b;
                else result = -1;
            } else {
                if (c > a) result = c;
                else result = b;
            }
            return result;
        }
    };
    

Log in to reply
 

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