代码随想录算法训练营day 14 | Leetcode 144

Leetcode 144 前序遍历

使用递归遍历。

class Solution {
public:
    vector<int> preorderTraversal(TreeNode* root) {
        vector<int> result;
        stack<TreeNode*> stTree;
        if(root == NULL) {return result;}
        TreeNode* cur;
        stTree.push(root);
        while(!stTree.empty()){
            cur = stTree.top();
            stTree.pop();
            result.push_back(cur -> val);
            if(cur -> right != NULL) {stTree.push(cur -> right);}
            if(cur -> left != NULL) {stTree.push(cur -> left);}
        }
        return result;
    }
};

Leetcode 94 中序遍历

因为中序遍历实际节点的访问顺序与处理顺序(中序遍历顺序)并不相同,总是先访问中,而非左,因此需要用一个指针控制访问节点。

class Solution {
public:
    vector<int> inorderTraversal(TreeNode* root) {
        stack<TreeNode*> st;
        vector<int> result;
        if(root == NULL) {return result;}
        TreeNode* cur = root;
        while(cur != NULL || !st.empty()){
            if(cur != NULL){
                st.push(cur);
                cur = cur -> left;
            }
            else{
                cur = st.top();
                st.pop();
                result.push_back(cur -> val);
                cur = cur -> right;
            }
        }
        return result;
    }
};

Leetcode 145 后序遍历

后序的顺序是左右中,可以先中右左,再翻转结果。

class Solution {
public:
    vector<int> postorderTraversal(TreeNode* root) {
        stack<TreeNode*> st;
        vector<int> result;
        if(root == NULL) {return result;}
        st.push(root);
        while(!st.empty()){
            TreeNode* node = st.top();
            st.pop();
            result.push_back(node -> val);
            if(node -> right) {st.push(node -> right);}
            if(node -> left) {st.push(node -> left);}
        }
        reverse(result.begin(), result.end());
        return result;
    }
};

Leetcode 226 翻转二叉树

使用递归法,对一个root,翻转它的左右子节点,再翻转左右子树。递归问题需要明确函数参数及返回值,递归结束条件,单层递归的过程。

class Solution {
public:
    TreeNode* invertTree(TreeNode* root) {
        if(root == NULL) return root;
        swap(root -> left, root -> right);
        invertTree(root -> left);
        invertTree(root -> right);
        return root;
    }
};

Leetcode 101 对称二叉树

再次使用递归,相当于每次判断两棵对称子树的根是否相等;

class Solution {
public:
    bool isRoot(TreeNode* L, TreeNode* R){
        if(L != NULL && R == NULL) {return false;}
        else if(L == NULL && R != NULL) {return false;}
        else if(L == NULL && R == NULL) {return true;}
        else if(L -> val != R -> val) {return false;}
        bool outside = isRoot(L -> left, R -> right);
        bool inside = isRoot(L -> right, R -> left);
        return inside&&outside;
    }
    bool isSymmetric(TreeNode* root) {
        if(root == NULL) return true;
        return isRoot(root -> left, root -> right);
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值