- leetcode--tree
- 144. Binary Tree Preorder Traver
- 144. Binary Tree Preorder Traver
- 字节跳动 144. Binary Tree Preorder T
- 144. Binary Tree Preorder Traver
- 144. Binary Tree Preorder Traver
- 144. Binary Tree Preorder Traver
- 144. Binary Tree Preorder Traver
- 144. Binary Tree Preorder Traver
- 144. Binary Tree Preorder Traver
Given a binary tree, return the preorder traversal of its nodes' values.
把访问到的右子树的地址压入栈:之后再根据栈是否为空,遍历所有的右子树,同时继续对新的右子树做压栈:
/**
* 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:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> ans;
stack<TreeNode*> st;
while(root)
{
ans.push_back(root->val);
if (root->right)
st.push(root->right);
root = root->left;
}
TreeNode *P=NULL;
while(!st.empty())
{
P = st.top();
st.pop();
while(P){
ans.push_back(P->val);
if(P->right) st.push(P->right);
P = P->left;
}
}
return ans;
}
};
网友评论