迭代法+递归法

二叉树的镜像

http://www.nowcoder.com/questionTerminal/a9d0ecbacef9410ca97463e4a5c83be7

class Solution {
public:
    TreeNode* Mirror(TreeNode* pRoot) {
        if(!pRoot) return nullptr;
        //使用一个stack
        stack<TreeNode*> stackTreeNode;
        stackTreeNode.push(pRoot);

        while(!stackTreeNode.empty()){
            TreeNode* pNode=stackTreeNode.top();
            stackTreeNode.pop();

            TreeNode* pTmp=pNode->left;
            pNode->left=pNode->right;
            pNode->right=pTmp;

            if(pNode->left)
                stackTreeNode.push(pNode->left);
            if(pNode->right)
                stackTreeNode.push(pNode->right);       
        }
        return pRoot;
    }
};
class Solution {
public:
    TreeNode* Mirror(TreeNode* pRoot) {
        if(!pRoot) return nullptr;
        if(!pRoot->left && !pRoot->right) return pRoot; 

        TreeNode* pTmp=pRoot->left;
        pRoot->left=pRoot->right;
        pRoot->right=pTmp;

        if(pRoot->left) Mirror(pRoot->left);
        if(pRoot->right) Mirror(pRoot->right);

        return pRoot;
    }
};
全部评论

相关推荐

09-25 00:00
已编辑
电子科技大学 Java
球球与墩墩:这不是前端常考的对象扁平化吗,面试官像是前端出来的 const flattern = (obj) => { const res = {}; const dfs = (curr, path) => { if(typeof curr === 'object' && curr !== null) { const isArray = Array.isArray(curr); for(let key in curr) { const newPath = path ? isArray ? `${path}[${key}]` : `${path}.${key}` : key; dfs(curr[key], newPath); } } else { res[path] = curr } } dfs(obj); return res; }
查看3道真题和解析
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务