1. 程式人生 > 其它 >144. 二叉樹的前序遍歷(非遞迴)

144. 二叉樹的前序遍歷(非遞迴)

144. 二叉樹的前序遍歷

難度簡單

給你二叉樹的根節點root,返回它節點值的前序遍歷。

示例 1:

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

示例 2:

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

示例 3:

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

示例 4:

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

示例 5:

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

提示:

  • 樹中節點數目在範圍[0, 100]
  • -100 <= Node.val <= 100

非遞迴方法:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 
*/ class Solution { public: vector<int> preorderTraversal(TreeNode* root) { if(root == nullptr) return {}; stack<TreeNode* >s; vector<int> ans; while(root || !s.empty()){ while(root){ ans.push_back(root->val); s.push(root); root
= root->left; } root = s.top(); s.pop(); root = root->right; } return ans; } };