4
/ \
2 7
/ \ / \
1 3 6 9
to
4
/ \
7 2
/ \ / \
9 6 3 1
不用多說了,就是反轉二元樹
方法有好幾種。我這邊用最快的方法BFS的作法來做
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode* invertTree(TreeNode* root) { if(nullptr == root) return root; stack<TreeNode*> myQueue; // our queue to do BFS myQueue.push(root); // push very first item - root while(!myQueue.empty()){ // run until there are nodes in the queue TreeNode *node = myQueue.top(); // get element from queue myQueue.pop(); // remove element from queue if(node->left != nullptr){ // add left kid to the queue if it exists myQueue.push(node->left); } if(node->right != nullptr){ // add right kid myQueue.push(node->right); } // invert left and right pointers swap(node->left, node->right); } return root; } };
沒有留言 :
張貼留言