1classSolution {2public:3vector<int> inorderTraversal(TreeNode *root) {4vector<int>result;5TreeNode *p =root;6while(p) {7if(p->left) {8TreeNode *q = p->left;9while(q->right && q->right !=p) {10q = q->right;11}12if(q->right ==p) {13result.push_back(p->val);14q-...
* Source : https://oj.leetcode.com/problems/binary-tree-inorder-traversal/ * * * Given a binary tree, return the inorder traversal of its nodes' values. * * For example: * Given binary tree {1,#,2,3}, * * 1 * \ * 2 * / * 3 * * return [1,3,2]. * * Note: Recursi...
来自专栏 · leetcode每日斩 题目 Given a binary tree, return the inorder traversal of its nodes' values. For example: Given binary tree [1,null,2,3], return [1,3,2]. Note: Recursive solution is trivial, could you do it iteratively? 解析 嘻嘻,最近因为马上要面试,就回忆一下树的遍历,快...
/** * 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> inorderTraversal(TreeNode* root) { vector<int> ret; if(...
Given preorder and inorder traversal of a tree, construct the binary tree. 二分法 复杂度 时间O(N^2) 空间 O(N) 思路 我们先考察先序遍历序列和中序遍历序列的特点。对于先序遍历序列,根在最前面,后面部分存在一个分割点,前半部分是根的左子树,后半部分是根的右子树。对于中序遍历序列,根在中间部分...
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 =
** Inorder Traversal: left -> root -> right ** Preoder Traversal: root -> left -> right ** Postoder Traveral: left -> right -> root 记忆方式:order的名字指的是root在什么位置。left,right的相对位置是固定的。 图片来源:https://leetcode.com/articles/binary-tree-right-side-view/ ...
名字叫做, morrois traversal, 自己写了下: My code: /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */publicclassSolution{publicList<Integer>inorderTraversal(TreeNoderoot){List...
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]]
TreeNode *t = stk.top(); rs.push_back(t->val); stk.pop(); flag = true; if (t->right) { stk.push(t->right); flag = false; } } return rs; } 或者如下,leetcode上解说的算法: vector<int> inorderTraversal(TreeNode *root) ...