leetcode 1026. Maximum Difference Between Node and Ancestor

leetcode 1026. Maximum Difference Between Node and Ancestor

题意:求一颗二叉树的一条链中的最大差值。

思路:找到每一条链,再找这条链中最大差值。

/**
 * 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 maxAncestorDiff(TreeNode* root) {
        ans = 0;
        vector now;
        dfs(root,now);
        return ans;
    }
    
    void dfs(TreeNode* root,vector& now)
    {
        if(root == nullptr)
        {
            int min_val = 100010;
            int max_val = -1;
            for(int i =0 ;ival);
        
        dfs(root->left,now);
        dfs(root->right,now);
        
        now.pop_back();
    }
private:
    int ans;
};

 

你可能感兴趣的:(LeetCode)