Leetcode 653. Two Sum IV - Input is a BST

版权声明:博客文章都是作者辛苦整理的,转载请注明出处,谢谢! https://blog.csdn.net/Quincuntial/article/details/86716528

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Two Sum IV - Input is a BST

2. Solution

  • Version 1
/**
 * 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:
    bool findTarget(TreeNode* root, int k) {
        vector<int> numbers;
        inorderTraverse(root, numbers);
        for(int val : numbers) {
        	if(k - val == val) {
        		return false;
        	}
        	else if(search(root, k - val)) {
        		return true;
        	}
        }
        return false;
    }

private:
	void inorderTraverse(TreeNode* root, vector<int>& numbers) {
		if(!root) {
			return;
		}
		inorderTraverse(root->left, numbers);
		numbers.push_back(root->val);
		inorderTraverse(root->right, numbers);
	}

	bool search(TreeNode* root, int target) {
        if(!root) {
            return false;
        }
		if(root->val == target) {
			return true;
		}
		else if(root->val > target) {
			return search(root->left, target);
		}
		else {
			return search(root->right, target);
		}
	}
};
  • Version 2
/**
 * 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:
    bool findTarget(TreeNode* root, int k) {
        return traverse(root, root, k);
    }

private:
	bool traverse(TreeNode* root, TreeNode* head, int k) {
		if(root->left && traverse(root->left, head, k)) {
			return true;
		}
		if(root->right && traverse(root->right, head, k)) {
			return true;
		}
		if(k - root->val == root->val) {
        	return false;
        }
		return search(head, k - root->val);
	}

	bool search(TreeNode* root, int target) {
		if(!root) {
			return false;
		}
		if(root->val == target) {
			return true;
		}
		else if(root->val > target) {
			return search(root->left, target);
		}
		else {
			return search(root->right, target);
		}
	}
};

Reference

  1. https://leetcode.com/problems/two-sum-iv-input-is-a-bst/description/

没有更多推荐了,返回首页