题目:
Given a binary tree, return the preorder traversal of its nodes’ values.
解释:
二叉树前序遍历。需要额外写一个函数。
python代码:
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def preorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
#递归写法
result=[]
def pre(root,result):
if root==None:
return None
result.append(root.val)
pre(root.left,result)
pre(root.right,result)
pre(root,result)
return result
c++代码:
/**
* 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> result;
pre(root,result);
return result;
}
void pre(TreeNode* root ,vector<int>&result){
if(root)
{
result.push_back(root->val);
pre(root->left,result);
pre(root->right,result);
}
}
};
用非递归的方法解决,二叉树的三种dfs中,前序遍历的非递归形式最好写。因为前序遍历是先遍历左子树再遍历右子树,所以先把右子树入栈,再把左子树入栈(其实就是和dfs反着看?,只要记住这点就够了:
python代码:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def preorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if not root:
return []
result=[]
stack=[]
stack.append(root)
while stack:
tmp=stack.pop()
result.append(tmp.val)
if tmp.right:
stack.append(tmp.right)
if tmp.left:
stack.append(tmp.left)
return result;
c++代码;
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
#include <stack>
using namespace std;
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
stack<TreeNode*>_stack;
vector<int> result;
if (!root)
return result;
_stack.push(root);
while(!_stack.empty())
{
TreeNode *tmp=_stack.top();
_stack.pop();
result.push_back(tmp->val);
if(tmp->right)
_stack.push(tmp->right);
if (tmp->left)
_stack.push(tmp->left);
}
return result;
}
};
总结:
cpp,注意定义函数的时候形式参数是引用…cpp确实比python需要注意的地方多。
注意用非递归的方法时,先把右结点入栈,再把左结点入栈。