1. 程式人生 > 其它 >GPIO模組:點亮led燈

GPIO模組:點亮led燈

94. 二叉樹的中序遍歷

給定一個二叉樹的根節點 root ,返回 它的 中序 遍歷 。

 

示例 1:

輸入:root = [1,null,2,3]
輸出:[1,3,2]

示例 2:

輸入:root = []
輸出:[]

示例 3:

輸入:root = [1]
輸出:[1]

 

提示:

  • 樹中節點數目在範圍 [0, 100] 內
  • -100 <= Node.val <= 100
 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
6 * TreeNode *right; 7 * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 * }; 11 */ 12 class Solution { 13 public:
14 vector<int> preorderTraversal(TreeNode* root) { 15 vector<int> ans; 16 if (root == nullptr) { 17 return ans; 18 } 19 stack<TreeNode *> s; 20 s.push(root); 21 while (!s.empty()) { 22 TreeNode *tmpNode = s.top();
23 s.pop(); 24 if (tmpNode != nullptr) { 25 if (tmpNode->right != nullptr) { 26 s.push(tmpNode->right); 27 } 28 s.push(tmpNode); 29 s.push(nullptr); 30 if (tmpNode->left != nullptr) { 31 s.push(tmpNode->left); 32 } 33 } else { 34 tmpNode = s.top(); 35 s.pop(); 36 ans.push_back(tmpNode->val); 37 } 38 } 39 return ans; 40 } 41 };