标签:treenode order public for leetcode tree node 分享 amp cto
前序遍历的递归解法:
方法一C++:
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 vector<int> preorderTraversal(TreeNode* root) { 13 //二叉树前序遍历的递归写法, 14 vector<int> res; 15 preorder(root,res); 16 return res; 17 } 18 void preorder(TreeNode* root,vector<int> &res){ 19 if(root==NULL) return; 20 res.push_back(root->val); 21 if(root->left) preorder(root->left,res); 22 if(root->right) preorder(root->right,res); 23 } 24 };
前序遍历的非递归方法:
C++代码:
leetcode 144. Binary Tree Preorder Traversal 二叉树的前序遍历
标签:treenode order public for leetcode tree node 分享 amp cto
原文地址:https://www.cnblogs.com/joelwang/p/10336343.html