否则,我们应访访问当前节点的右孩子(入栈)。 // C++ CODE: classSolution {public: vector<int> postorderTraversal(TreeNode*root) { stack<TreeNode*>s; vector<int>result;while(root){ s.push(root); root= root->left; }while(!s.empty(
1classSolution {2public:3vector<int> preorderTraversal(TreeNode *root) {4vector<int>result;5TreeNode *p =root;6while(p) {7if(!p->left) {8result.push_back(p->val);9p = p->right;10}else{11TreeNode *q = p->left;12while(q->right && q->right !=p) {13q = q->right;14}1...
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level). For example: Given binary tree [3,9,20,null,null,15,7], 代码语言:javascript 代码运行次数:0 运行 AI代码解释 3/\920/\157 return its level order traversal as: 代码...
Leetcode 之Binary Tree Postorder Traversal(45) 层序遍历,使用队列将每层压入,定义两个队列来区分不同的层。 vector<vector<int>> levelorderTraversal(TreeNode *root) { vector<vector<int>>result; vector<int>tmp;//通过两个queue来区分不同的层次queue<TreeNode *>current,next; TreeNode*p =root; curr...
Can you solve this real interview question? Binary Tree Preorder Traversal - Given the root of a binary tree, return the preorder traversal of its nodes' values. Example 1: Input: root = [1,null,2,3] Output: [1,2,3] Explanation: [https://assets.l
It's essential to be mindful of boundary conditions when invoking the recursive function. 3. Code: Lists as parameters Indices as parameters High efficiency indices as parameters 3.1. Explaination of the Code: 3.1.1 Lists as parameters: Start by defining the function buildTree that takes the...
Can you solve this real interview question? Binary Tree Level Order Traversal - Given the root of a binary tree, return the level order traversal of its nodes' values. (i.e., from left to right, level by level). Example 1: [https://assets.leetcode.c
Leetcode 之Binary Tree Inorder Traversal(43) 树的中序遍历。先不断压入左结点至末尾,再访问,再压入右结点。注意和先序遍历的比较 vector<int> inorderTraversal(TreeNode *root) { vector<int>result; stack<TreeNode *>s; TreeNode*p =root;while(!s.empty() || p !=nullptr)...
102. 二叉树的层序遍历 - 给你二叉树的根节点 root ,返回其节点值的 层序遍历 。 (即逐层地,从左到右访问所有节点)。 示例 1: [https://assets.leetcode.com/uploads/2021/02/19/tree1.jpg] 输入:root = [3,9,20,null,null,15,7] 输出:[[3],[9,20],[15,7]]
145. 二叉树的后序遍历 - 给你一棵二叉树的根节点 root ,返回其节点值的 后序遍历 。 示例 1: 输入:root = [1,null,2,3] 输出:[3,2,1] 解释: [https://assets.leetcode.com/uploads/2024/08/29/screenshot-2024-08-29-202743.png] 示例 2: 输入:root =