BM32 合并二叉树
已知两颗二叉树,将它们合并成一颗二叉树。合并规则是:都存在的结点,就将结点值加起来,否则空的位置就由另一个树的结点来代替。例如:
两颗二叉树是:
解法(深搜)
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
/**
*
* @param t1 TreeNode类
* @param t2 TreeNode类
* @return TreeNode类
*/
typedef struct TreeNode* pnode;
static inline int get_val(pnode root)
{
return root?root->val:0;
}
static inline pnode get_left(pnode root)
{
return root?root->left:NULL;
}
static inline pnode get_right(pnode root)
{
return root?root->right:NULL;
}
struct TreeNode* mergeTrees(struct TreeNode* t1, struct TreeNode* t2 ) {
// write code here
if(!t1&&!t2)
{
return NULL;
}
pnode root = malloc(sizeof(struct TreeNode));
root->val = get_val(t1) + get_val(t2);
root->left = mergeTrees( get_left (t1) , get_left (t2 ));
root->right = mergeTrees( get_right(t1) , get_right(t2 ));
return root;
}