题目
给你二叉树的根节点 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]
解题
方法一:递归
python解法
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def preorderTraversal(self, root: TreeNode) -> List[int]: def preorder(root: TreeNode): if not root: return res.append(root.val) preorder(root.left) preorder(root.right) res = list() preorder(root) return res
c++解法
class Solution { public: void preorder(TreeNode* root,vector<int>& res){ if(!root) return; res.push_back(root->val); preorder(root->left,res); preorder(root->right,res); } vector<int> preorderTraversal(TreeNode* root) { vector<int> res; preorder(root,res); return res; } };
java解法
class Solution { List<Integer> res=new LinkedList<>(); void dfs(TreeNode node){ if(node==null) return; res.add(node.val); dfs(node.left); dfs(node.right); return; } public List<Integer> preorderTraversal(TreeNode root) { dfs(root); return res; } }
方法二:迭代
python解法
模板解法:
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def preorderTraversal(self, root: TreeNode) -> List[int]: if not root: return [] cur=root res=[] stack=[] while stack or cur: while cur: res.append(cur.val) stack.append(cur) cur = cur.left cur = stack.pop() cur = cur.right return res
常规解法:
class Solution: def preorderTraversal(self, root: TreeNode) -> List[int]: ans = [] if not root: return ans stack = [root] while stack: node = stack.pop() ans.append(node.val) if node.right: stack.append(node.right) if node.left: stack.append(node.left) return ans
先把右子节点压入堆栈,再是左节点压入堆栈,这样的话,左节点是先pop出来的。
c++解法
模板解法:
class Solution { public: vector<int> preorderTraversal(TreeNode* root) { if(!root) return {}; vector<int> res; TreeNode* cur=root; stack<TreeNode*> stack; while(!stack.empty()||cur){ while(cur){ res.push_back(cur->val); stack.push(cur); cur=cur->left; } cur=stack.top(); stack.pop(); cur=cur->right; } return res; } };
常规解法:
class Solution { public: vector<int> preorderTraversal(TreeNode* root) { if(!root) return {}; vector<int> res; stack<TreeNode*> stack; stack.push(root); while(!stack.empty()){ TreeNode* node=stack.top(); stack.pop(); res.push_back(node->val); if(node->right){ stack.push(node->right); } if(node->left){ stack.push(node->left); } } return res; } };
java解法
class Solution { public List<Integer> preorderTraversal(TreeNode root) { List<Integer> res=new LinkedList<>(); Stack<TreeNode> st=new Stack<>(); TreeNode cur=root; while(!st.isEmpty()||cur!=null){ while(cur!=null){ res.add(cur.val); st.push(cur); cur=cur.left; } cur=st.pop(); cur=cur.right; } return res; } }