Invert Binary Tree

Nov 05, 2017

第41天。

今天的题目是Invert Binary Tree:

Invert a binary tree.

     4
   /   \
  2     7
 / \   / \
1   3 6   9

to

     4
   /   \
  7     2
 / \   / \
9   6 3   1

Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so fuck off.

emmmm,挺出名的一道题目。

其实挺简单:

TreeNode* invertTre1e(TreeNode* root) {
    if (root == nullptr) return root;
    TreeNode *left = invertTree(root->right);
    TreeNode *right = invertTree(root->left);
    root->left = left;
    root->right = right;
    return root;
}

然后是迭代的方法:

TreeNode* invertTree(TreeNode *root) {
    stack<TreeNode *> st;
    st.push(root);
    TreeNode *ret =root;
    while(!st.empty()) {
        root = st.top();
        st.pop();
        if (root) {
            st.push(root->left);
            st.push(root->right);
            TreeNode *t = root->left;
            root->left = root->right;
            root->right = t;
        }
    }
    return ret;
}
LeetCodeLeetCodeTree

Palindrome Linked List

Reverse Linked List

comments powered by Disqus