leetcode之二叉树(easy)

404. Sum of Left Leaves

Find the sum of all left leaves in a given binary tree.

Example:

    3
   / \
  9  20
    /  \
   15   7

There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.
solutions: 

该题目的意思是让求一个二叉树的所有的左叶子节点的和,一般二叉树的题目,首先想到的是递归,并写出终止条件,如果一个节点的左孩子存在,并且该孩子节点的左子树和右子树都为空,那么该孩子节点为左叶子节点。

code:

/**
 * 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 sumOfLeftLeaves(TreeNode* root) 
    {
        if(!root)
        {
            return 0;
        }
        if(root->left&&!root->left->left&&!root->left->right)
        {
            return root->left->val+sumOfLeftLeaves(root->right);
        }
        return sumOfLeftLeaves(root->left)+sumOfLeftLeaves(root->right);
        
    }
};
100. Same Tree

Given two binary trees, write a function to check if they are equal or not.

Two binary trees are co

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool isSymmetric(TreeNode *root) {
        TreeNode *left, *right;
        if (!root)
            return true;
        
        queue<TreeNode*> q1, q2;
        q1.push(root->left);
        q2.push(root->right);
        while (!q1.empty() && !q2.empty()){
            left = q1.front();
            q1.pop();
            right = q2.front();
            q2.pop();
            if (NULL == left && NULL == right)
                continue;
            if (NULL == left || NULL == right)
                return false;
            if (left->val != right->val)
                return false;
            q1.push(left->left);
            q1.push(left->right);
            q2.push(right->right);
            q2.push(right->left);
        }
        return true;
    }
};

nsidered equal if they are structurally identical and the nodes have the same value.

解题思路:

题目要求判断两个二叉树是否相同(递归)

代码如下:

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

思路:改题目要求判断一棵树是不是对称的。给的例子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 isSymmetric(TreeNode* root) 
    {
        if(root==NULL)
        {
            return true;
        }
        return isEqual(root->left,root->right);
        
    }
    bool isEqual(TreeNode* tree1,TreeNode * tree2)
    {
        if(tree1==NULL||tree2==NULL)
        {
            if(tree1==tree2)
            {
                return true;
            }
            return false;
        }
        if(tree1->val==tree2->val)
        {
            return isEqual(tree1->right,tree2->left)&&isEqual(tree1->left,tree2->right);
        }
        return false;
    }
};

迭代算法

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool isSymmetric(TreeNode *root) {
        TreeNode *left, *right;
        if (!root)
            return true;
        
        queue<TreeNode*> q1, q2;
        q1.push(root->left);
        q2.push(root->right);
        while (!q1.empty() && !q2.empty()){
            left = q1.front();
            q1.pop();
            right = q2.front();
            q2.pop();
            if (NULL == left && NULL == right)
                continue;
            if (NULL == left || NULL == right)
                return false;
            if (left->val != right->val)
                return false;
            q1.push(left->left);
            q1.push(left->right);
            q2.push(right->right);
            q2.push(right->left);
        }
        return true;
    }
};
104. Maximum Depth of Binary Tree

Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

解题思路:递归

代码:

/**
 * 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 maxDepth(TreeNode* root) 
    {
        if(root==NULL)
        {
            return 0;
        }
        return max(maxDepth(root->left),maxDepth(root->right))+1;
        
    }
};

108. Convert Sorted Array to Binary Search Tree

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

解题思路:题目的意思是给定一个升序的数组,将其转换成一个高度平衡的二叉搜索树。平衡二叉搜索树,那么它的根节点应该是该数组的中位数,那么根节点的左子树应该是前半个数组的平衡二叉搜索树。根的右子树应该是后半个数组的平衡二叉树。所以该题目可以用二叉搜索来解决。

代码如下:

/**
 * 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) 
    {
        TreeNode * root=new TreeNode(-1);
        if(nums.size()==0)
        {
            return NULL;
        }
        if(nums.size()==1)
        {
            root->val=nums[0];
            return root;
        }
        int middle=nums.size()/2;
        root->val=nums[middle];
        vector<int> left(nums.begin(),nums.begin()+middle);
        root->left=sortedArrayToBST(left);
        vector<int> right(nums.begin()+middle+1,nums.end());
        root->right=sortedArrayToBST(right);
        return root;
        
    }
};

114. Flatten Binary Tree to Linked List

Given a binary tree, flatten it to a linked list in-place.

For example,
Given

         1
        / \
       2   5
      / \   \
     3   4   6

The flattened tree should look like:
   1
    \
     2
      \
       3
        \
         4
          \
           5
            \
             6
/**
 * 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:
    void flatten(TreeNode* root) 
    {
    	while(root)
    	{
    		if(root->left==NULL)
    		{
    			root=root->right;
    		}
    		else
    		{
    			if(root->right)
    			{
    				TreeNode *l=root->left;
    				while(l->right)
    				{
    					l=l->right;
    				}
    				l->right=root->right;

    			}
    			root->right=root->left;
    			root->left=NULL;
    			root=root->right;
    		}
    	}
        
    }
};

111. Minimum Depth of Binary Tree


Given a binary tree, find its minimum depth.

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

/**
 * 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 minDepth(TreeNode* root) 
    {
        if(root==NULL)
        {
            return 0;
        }
        return min(minDepth(root->left),minDepth(root->right))+1;
        
    }
};

112. Path Sum

Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.

For example:
Given the below binary tree and  sum = 22 ,
              5
             / \
            4   8
           /   / \
          11  13  4
         /  \      \
        7    2      1

return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.

解题思路:采用递归,进行深度优先遍历,如果当前节点为叶子节点,其值等于sum,则返回true。如果当前节点为空,则返回false。

代码:

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

113. Path Sum II

Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.

For example:
Given the below binary tree and  sum = 22,
              5
             / \
            4   8
           /   / \
          11  13  4
         /  \    / \
        7    2  5   1

return

[
   [5,4,11,2],
   [5,8,4,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:
    vector<vector<int>> pathSum(TreeNode* root, int sum) 
    {
        vector<vector<int>>ret;
        vector<int> indices;
        dfs(root,ret,indices,sum);
        return ret;
    }
    void dfs(TreeNode *root,vector<vector<int>>&ret,vector<int>&indices,int sum)
    {
        if(root==NULL)
        {
            return;
        }
        indices.push_back(root->val);
        if(root->left==NULL&&root->right==NULL&&root->val==sum)
        {
            ret.push_back(indices);
        }
        dfs(root->left,ret,indices,sum-root->val);
        dfs(root->right,ret,indices,sum-root->val);
        indices.pop_back();
    }
};




437. Path Sum III

You are given a binary tree in which each node contains an integer value.

Find the number of paths that sum to a given value.

The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to child nodes).

The tree has no more than 1,000 nodes and the values are in the range -1,000,000 to 1,000,000.

Example:

root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8

      10
     /  \
    5   -3
   / \    \
  3   2   11
 / \   \
3  -2   1

Return 3. The paths that sum to 8 are:

1.  5 -> 3
2.  5 -> 2 -> 1
3. -3 -> 11
解题思路:对于每一个节点,有两种选择,第一种,经过这个点的路径,不经过这个节点的路径。比如,从根节点开始,我们需要求得是,经过该节点的路径和为sum的和不经过这个节点的和为sum的路径,具体如下:

/**
 * 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 pathSum(TreeNode* root, int sum) 
    {
        if(root==NULL)
        {
            return 0;
            
        }
        return sumUp(root,0,sum)+pathSum(root->left,sum)+pathSum(root->right,sum);
    }
    int sumUp(TreeNode * root,int prev,int sum)
    {
        if(root==NULL)
        {
            return 0;
        }
        int cur=root->val+prev;
        return (cur==sum)+sumUp(root->left,cur,sum)+sumUp(root->right,cur,sum);
    }
};
110. Balanced Binary Tree

Given a binary tree, determine if it is height-balanced.

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.

解题思路:在这里采用后续遍历的方法,记录每一个节点的深度,这样避免了重复计算。代码如下:

/**
 * 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 isBalanced(TreeNode* root) 
    {
        int depth=0;
        return isBalanced(root,depth);
    }
    bool isBalanced(TreeNode * root,int &depth)
    {
        if(root==NULL)
        {
            depth=0;
            return true;
        }
        int left=0;
        int right=0;
        if(isBalanced(root->left,left)&&isBalanced(root->right,right))
        {
            int diff=left-right;
            if(abs(diff)<=1)
            {
                depth=max(left,right)+1;
                return true;
            }
        }
        return false;
    }
};
257. Binary Tree Paths

Given a binary tree, return all root-to-leaf paths.

For example, given the following binary tree:

   1
 /   \
2     3
 \
  5

All root-to-leaf paths are:

["1->2->5", "1->3"]

解题思路:

递归来求解:返回所有的路径即可,比如从根节点出发,如果根节点为叶子结点,则该路径结束,将该路径添加到结果中去,如果左子树存在,则继续遍历左子树的路径,右子树同理可得。代码如下:

/**
 * 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:
    vector<string> binaryTreePaths(TreeNode* root) 
    {
        vector<string> result;
        string ret="";
        if(root==NULL)
        {
            return result;
        }
        ret=ret+to_string(root->val);
        dfs(result,ret,root);
        return result;
        
    }
    void dfs(vector<string>&result,string ret,TreeNode *root)
    {
        if(root->left==NULL&&root->right==NULL)
        {
            result.push_back(ret);
            return;
        }
        if(root->left)
        {
            dfs(result,ret+"->"+to_string(root->left->val),root->left);
        }
        if(root->right)
        {
            dfs(result,ret+"->"+to_string(root->right->val),root->right);
        }
    }
};

226. Invert Binary Tree

Invert a binary tree.

     4
   /   \
  2     7
 / \   / \
1   3 6   9
to
     4
   /   \
  7     2
 / \   / \
9   6 3   1
Trivia:
This problem was inspired by  this original tweet  by  Max Howell :
Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so fuck off.
思路如下:左右子树进行反转,将反转后的左子树赋作为根节点的右子树,反转后的右子树为根节点的左子树。代码如下:
/**
 * 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* invertTree(TreeNode* root) 
    {
        if(root==NULL||root->left==NULL&&root->right==NULL)
        {
            return root;
        }
        TreeNode * left=root->left;
        TreeNode * right=root->right;
        root->left=invertTree(right);
        root->right=invertTree(left);
        return root;
        
    }
};

235. Lowest Common Ancestor of a Binary Search Tree

Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.

According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”

        _______6______
       /              \
    ___2__          ___8__
   /      \        /      \
   0      _4       7       9
         /  \
         3   5

For example, the lowest common ancestor (LCA) of nodes 2 and 8 is 6. Another example is LCA of nodes 2and 4 is 2, since a node can be a descendant of itself according to the LCA definition.

解题思路:一定要看清楚题目意思:二叉搜索树,这样就简单了;代码如下:
/**
 * 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* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) 
    {
        if(p->val<=root->val&&q->val>=root->val||p->val>=root->val&&q->val<=root->val)
        {
            return root;
        }
        if(p->val>root->val&&q->val>root->val)
        {
            return lowestCommonAncestor(root->right,p,q);
        }
        else
        {
            return lowestCommonAncestor(root->left,p,q);
        }
    }
};

236. Lowest Common Ancestor of a Binary Tree

Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”

        _______3______
       /              \
    ___5__          ___1__
   /      \        /      \
   6      _2       0       8
         /  \
         7   4

For example, the lowest common ancestor (LCA) of nodes 5 and 1 is 3. Another example is LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.

解题思路:判断两个二叉树的最近公共祖先。给定一棵树,另外给定两个节点,如果其中一个节点为根节点,那么返回肯定是根节点。否则递归左子树和右子树。如果一颗二叉树遍历到其中的一个节点,就返回该节点。代码如下:

/**
 * 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* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) 
    {
        if(root==NULL)
        {
            return root;
        }
        if(root==p||root==q)
        {
            return root;
        }
        TreeNode * left=lowestCommonAncestor(root->left,p,q);
        TreeNode * right=lowestCommonAncestor(root->right,p,q);
        if(left!=NULL&&right!=NULL)
        {
            return root;
        }
        if(left!=NULL)
        {
            return left;
        }
        if(right!=NULL)
        {
            return right;
        }
        return NULL;
        
    }
};

501. Find Mode in Binary Search Tree

Given a binary search tree (BST) with duplicates, find all the mode(s) (the most frequently occurred element) in the given BST.

Assume a BST is defined as follows:

  • The left subtree of a node contains only nodes with keys less than or equal to the node's key.
  • The right subtree of a node contains only nodes with keys greater than or equal to the node's key.
  • Both the left and right subtrees must also be binary search trees.

For example:
Given BST [1,null,2,2],

   1
    \
     2
    /
   2

return [2].

Note: If a tree has more than one mode, you can return them in any order.

解题思路:该题目的意思是求一颗二叉树的众数。遍历一遍,然后hash存储即可。代码如下:

/**
 * 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:
    vector<int> findMode(TreeNode* root) 
    {
        vector<int> result;
        max=0;
        middletraverse(root);
        for(auto it : hash)
        {
            if(it.second==max)
            {
                result.push_back(it.first);
            }
        }
        return result;
    }
    void middletraverse(TreeNode * root)
    {
        if(root==NULL)
        {
            return;
        }
        middletraverse(root->left);
        hash[root->val]=hash[root->val]+1;
        if(hash[root->val]>max)
        {
            max=hash[root->val];
        }
        middletraverse(root->right);
    }
private:
    unordered_map<int,int> hash;
    int max;
};

543. Diameter of Binary Tree

iven a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of thelongest path between any two nodes in a tree. This path may or may not pass through the root.

Example:
Given a binary tree 

          1
         / \
        2   3
       / \     
      4   5    

Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].

Note: The length of path between two nodes is represented by the number of edges between them.

解题思路:该题目的意思是求二叉树的直径,通过给的例子来看,一颗二叉树的直径是左子树的最大直径,右子树的最大直径,左子树与右子树的高度之和中的最大值。

代码:

/**
 * 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 diameterOfBinaryTree(TreeNode* root) 
    {
        if(root==NULL)
        {
            return 0;
        }
      return max(getHeight(root->left)+getHeight(root->right),max(diameterOfBinaryTree(root->left),diameterOfBinaryTree(root->right)));
      //  return getHeight(root->left)+getHeight(root->right);
    }
    int getHeight(TreeNode *root)
    {
        if(root==NULL)
        {
            return 0;
        }
        if(hash.count(root))
        {
            return hash[root];
        }
        hash[root]=max(getHeight(root->left),getHeight(root->right))+1;
        return hash[root];

    }
private:
    unordered_map<TreeNode*,int> hash;
};
563. Binary Tree Tilt

Given a binary tree, return the tilt of the whole tree.

The tilt of a tree node is defined as the absolute difference between the sum of all left subtree node values and the sum of all right subtree node values. Null node has tilt 0.

The tilt of the whole tree is defined as the sum of all nodes' tilt.

Example:

Input: 
         1
       /   \
      2     3
Output: 1
Explanation: 
Tilt of node 2 : 0
Tilt of node 3 : 0
Tilt of node 1 : |2-3| = 1
Tilt of binary tree : 0 + 0 + 1 = 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:
    int findTilt(TreeNode* root) 
    {
        int ret=0;
        int sum=postTraverse(root,ret);
        return ret;
    }
    int postTraverse(TreeNode * root,int &ret)
    {
        if(root==NULL)
        {
            return 0;
        }
        int left=postTraverse(root->left,ret);
        int right=postTraverse(root->right,ret);
        ret=ret+abs(left-right);
        return left+right+root->val;
    }
};
572. Subtree of Another Tree

Given two non-empty binary trees s and t, check whether tree t has exactly the same structure and node values with a subtree of s. A subtree of s is a tree consists of a node in s and all of this node's descendants. The tree s could also be considered as a subtree of itself.

Example 1:
Given tree s:

     3
    / \
   4   5
  / \
 1   2
Given tree t:
   4 
  / \
 1   2
Return  true , because t has the same structure and node values with a subtree of s.

Example 2:
Given tree s:

     3
    / \
   4   5
  / \
 1   2
    /
   0
Given tree t:
   4
  / \
 1   2
Return  false .

解题思路:该题目的意思是判断一棵树是不是另一颗树的子树,很明显需要解决的第一个问题是如何判断两棵树是不是相等的问题,然后通过判断一棵树的子树是不是跟另一颗树相等即可。代码如下:

/**
 * 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 isSubtree(TreeNode* s, TreeNode* t) 
    {
        if(s==NULL&&t==NULL)
        {
            return true;
        }
        if(s==NULL||t==NULL)
        {
            return false;
        }
        if(isEqual(s,t)||isSubtree(s->left,t)||isSubtree(s->right,t))
        {
            return true;
        }
        return false;
    }
    bool isEqual(TreeNode*s,TreeNode*t)
    {
        if(s==NULL&&t==NULL)
        {
            return true;
        }
        if(s==NULL||t==NULL||s->val!=t->val)
        {
            return false;
        }
        return isEqual(s->left,t->left)&&isEqual(s->right,t->right);
    }
};

617. Merge Two Binary Trees


Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not.

You need to merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of new tree.

Example 1:

Input: 
	Tree 1                     Tree 2                  
          1                         2                             
         / \                       / \                            
        3   2                     1   3                        
       /                           \   \                      
      5                             4   7                  
Output: 
Merged tree:
	     3
	    / \
	   4   5
	  / \   \ 
	 5   4   7

解题思路:合并两棵树,很简单,根节点合并,然后左子树右子树分别合并即可。代码如下:

/**
 * 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* mergeTrees(TreeNode* t1, TreeNode* t2) 
    {
        TreeNode * root=new TreeNode(-1);
        if(t1==NULL&&t2==NULL)
        {
            return NULL;
        }
        if(t1==NULL||t2==NULL)
        {
            if(t1)
            {
                return t1;
            }
            if(t2)
            {
                return t2;
            }
        }
        root->val=t1->val+t2->val;
        root->left=mergeTrees(t1->left,t2->left);
        root->right=mergeTrees(t1->right,t2->right);
        return root;
    }
};












  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值