题解 | #合并二叉树#

合并二叉树

http://www.nowcoder.com/practice/7298353c24cc42e3bd5f0e0bd3d1d759

alt alt alt

 * struct TreeNode {
 *	int val;
 *	struct TreeNode *left;
 *	struct TreeNode *right;
 * };
 */

class Solution {
public:
    /**
     * 
     * @param t1 TreeNode类 
     * @param t2 TreeNode类 
     * @return TreeNode类
     */
    TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) {
        // write code here
        TreeNode* res_help = NULL;
        res_help = (t1 != NULL) ? t1 : t2;
        helper(t1, t2, res_help);
        
        return res_help;
    }
    void helper(TreeNode* t1, TreeNode* t2, TreeNode* res){
        TreeNode* T1L = (TreeNode*)t1;
        TreeNode* T1R = (TreeNode*)t1;
        TreeNode* T2L = (TreeNode*)t2;
        TreeNode* T2R = (TreeNode*)t2;
        TreeNode* cur = res;
        if(t1 != NULL && t2 != NULL){
            res->val = t1->val + t2->val;
            T1L = (t1->left != NULL) ? t1->left : NULL;
            T1R = (t1->right != NULL) ? t1->right : NULL;
            T2L = (t2->left != NULL) ? t2->left : NULL;
            T2R = (t2->right != NULL) ? t2->right : NULL;
            cur->left = (T1L != NULL) ? T1L : T2L;
            cur->right = (T1R != NULL) ? T1R : T2R;
            
        }
        else if(t1 != NULL && t2 ==NULL){
            res->val = t1->val;
            T1L = (t1->left != NULL) ? t1->left : NULL;
            T1R = (t1->right != NULL) ? t1->right : NULL;
            T2L = NULL;
            T2R = NULL;
            cur->left = (T1L != NULL) ? T1L : T2L;
            cur->right = (T1R != NULL) ? T1R : T2R;
        }
        else if(t1 == NULL && t2 != NULL){
            res->val = t2->val;
            T1L = NULL;
            T1R = NULL;
            T2L = (t2->left != NULL) ? t2->left : NULL;
            T2R = (t2->right != NULL) ? t2->right : NULL;
            cur->left = (T1L != NULL) ? T1L : T2L;
            cur->right = (T1R != NULL) ? T1R : T2R;
        }
        else{
            return;
        }
        
        helper(T1L, T2L, cur->left);
        helper(T1R, T2R, cur->right);
    }
};
全部评论

相关推荐

去B座二楼砸水泥地:不过也可以理解,这种应该没参加过秋招
点赞 评论 收藏
分享
10-30 22:18
已编辑
毛坦厂中学 C++
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务