同num8一样,此题考查的是二叉树的中序遍历,即先左子树再节点再右子树、
使用迭代法时,采用将节点和左子树均压入栈的方法,当左子树为NULL时,将top节点弹出,并存入结果列表,将next指针指向该节点的右子树
代码如下:
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<int> inorderTraversal(TreeNode *root) { vector<int> rs; #存储结果 stack<TreeNode *> nstack; TreeNode *next=root; while(next||!nstack.empty()){ while(next){ nstack.push(next); next=next->left; } next=nstack.top(); nstack.pop(); rs.push_back(next->val);#结果rs中先存入左子树节点值 next=next->right; } return rs; } };
递归法就比较简单了,代码如下:
# Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param root, a tree node # @return a list of integers def inorderTraversal(self, root): rs=[] if root!=None: rs=self.inorderTraversal(root.left)+[root.val]+self.inorderTraversal(root.right) return rs
时间: 2024-12-15 10:34:34