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;12
原题链接在此:https://leetcode.com/problems/binary-tree-level-order-traversal/ Given therootof a binary tree, returnthe level order traversal of its nodes' values. (i.e., from left to right, level by level). 给你一个二叉树,请你返回其按 层序遍历 得到的节点值。 (即逐层地,从左到右访...
vector<int> inorderTraversal(TreeNode* root) { vector<int> vec; if(root == NULL)return vec; inorder(root,vec); return vec; } }; 递归 class Solution { public: void inorder(TreeNode* root, vector<int> & vec) { if(root -> left != NULL) { inorder(root -> left,vec); } vec...
Leetcode 94: Binary Tree Inorder Traversal-中序遍历 自动驾驶搬砖师 一步一个台阶,一天一个脚印 一、题目描述 给定一个二叉树,返回它的中序遍历。 二、解题思路 2.1 递归法 时间复杂度 O(n) 空间复杂度 O(n) 2.2 迭代法 时间复杂度 O(n) 空间复杂度 O(n)(1) 同理创建一个Stack,然后按左/中/右...
The following code illustrates how to use the BinaryTree class to generate a binary tree with the same data and structure as binary tree (a) shown in Figure 2.BinaryTree<int> btree = new BinaryTree<int>(); btree.Root = new BinaryTreeNode<int>(1); btree.Root.Left = new BinaryTree...
public BinaryTree() { root = null; } public virtual void Clear() { root = null; } public BinaryTreeNode<T> Root { get { return root; } set { root = value; } } } The following code illustrates how to use theBinaryTreeclass to generate a binary tree with the same data and struc...
** 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/ ...
Pre-Order Traversal 三种解法: Recursive Iterate 用Stack Morris Traversal (好处是,Pre-Order和In-Order代码只有很小的改动) Morris Pre-Order Traversal (LeetCode 144) (Medium) 1...If left child is null, print the current node data. Move to right child. ...
Leetcode 之Binary Tree Postorder Traversal(45) 层序遍历,使用队列将每层压入,定义两个队列来区分不同的层。 vector<vector<int>> levelorderTraversal(TreeNode *root) { vector<vector<int>>result; vector<int>tmp;//通过两个queue来区分不同的层次queue<TreeNode *>current,next;...
Binary Tree Level Order Traversal II 题目链接 题目要求: Given a binary tree, return thebottom-up level ordertraversal of its nodes' values. (ie, from left to right, level by level from leaf to root). For example: Given binary tree{3,9,20,#,#,15,7}, ...