LeetCode 101. Symmetric Tree (对称二叉树) 108. Convert Sorted Array To BST(二叉搜索树)

101. Symmetric Tree (对称二叉树)

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

For example, this binary tree [1,2,2,3,4,4,3] is symmetric:

    1
   / \
  2   2
 / \ / \
3  4 4  3

But the following [1,2,2,null,3,null,3] is not:

    1
   / \
  2   2
   \   \
   3    3

Note:
Bonus points if you could solve it both recursively and iteratively.

代码:

/**
 * 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 isSymmetric(TreeNode* root) {
        if(root == NULL)
            return true;        
        return isSymmetric(root->left, root->right);
    }
    bool isSymmetric(TreeNode* p, TreeNode* q) {
        if(p == NULL && q == NULL)
            return true;
        if(p == NULL || q == NULL)
            return false;
        if(p->val == q->val)
            return isSymmetric(p->left, q->right)&&isSymmetric(p->right, q->left);
        return false;
    }
};

108 Convert Sorted Array To BST(二叉搜索树)

Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

Example:

Given the sorted array: [-10,-3,0,5,9],

One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:

      0
     / \
   -3   9
   /   /
 -10  5

代码:

/**
 * 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:
    TreeNode* sortedArrayToBST(vector<int>& nums) {
        return dfs(nums,0,nums.size()-1);
    }
    TreeNode* dfs(vector<int>& nums, int left, int right) {
        if(left>right) return NULL;
        int mid = (left +right)/2;
        TreeNode *root = (TreeNode *)malloc(sizeof(TreeNode));
        root->val = nums[mid];
        root->left = dfs(nums,left,mid-1);
        root->right = dfs(nums, mid+1, right);
        return root;
    }
};

猜你喜欢

转载自blog.csdn.net/yige__cxy/article/details/81626536