- Invert Binary Tree
Runtime: 4 ms, faster than 26.53% of C online submissions for Invert Binary Tree.
Memory Usage: 7.5 MB, less than 37.04% of C online submissions for Invert Binary Tree.
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
void dfs(struct TreeNode* r){
if(r==NULL)
return;
struct TreeNode* t;
t = r->left;
r->left = r->right;
r->right = t;
dfs(r->left);
dfs(r->right);
}
struct TreeNode* invertTree(struct TreeNode* root) {
dfs(root);
return root;
}
- 下面这种写法是错误,出不来结果, 猜测是函数栈的问题
用同样的方法,不另外写函数,在lintcode上用Java 提交是通过的。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
struct TreeNode* invertTree(struct TreeNode* root) {
if(root==NULL);
return NULL;
if(root->left!=NULL || root->right!=NULL){
struct TreeNode *tmp = root->left;
root->left = root->right;
root->right = tmp;
}
invertTree(root->left);
invertTree(root->right);
return root;
}
网友评论