题目 分析 按要求转换二叉树: 分析转换要求,发现,新的二叉树是按照原二叉树的先序遍历结果构造的单支二叉树(只有右子树). 发现规则,便容易处理了.得到先序遍历,构造即可. AC代码 /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NUL…
题目 Given inorder and postorder traversal of a tree, construct the binary tree. Note: You may assume that duplicates do not exist in the tree. Show Tags Show Similar Problems 分析 跟上一道题同样的道理. AC代码 class Solution { public: template <typename Iter> TreeN…
题目 Given preorder and inorder traversal of a tree, construct the binary tree. Note: You may assume that duplicates do not exist in the tree. 分析 给定一颗二叉树的前序和中序遍历序列,求该二叉树. 我们手动做过很多这样的题目,掌握了其规则~ 前序遍历第一个元素为树的root节点,然后在中序序列中查找该值,元素左侧为左子树,右侧为右子树: 求出左子树个数cou…
题目: Given a binary tree, determine if it is height-balanced. For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1. 思路: 题目的大意是[判断一个二叉树是不是平衡二叉树 首先了解…
题目 Given a binary tree, determine if it is height-balanced. For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1. 分析 判断给定二叉树是否为二叉平衡树,即任一节点的左右子树高度差…
题目 分析 交换二叉树的左右子树. 递归非递归两种方法实现. AC代码 class Solution { public: //递归实现 TreeNode* invertTree(TreeNode* root) { if (!root) return root; TreeNode *tmp = root->left; root->left = invertTree(root->right); root->right = invertTree(tmp); return root; }…
提示中说明了,改动后的链表相当于原树的前序遍历结果.前序遍历是根左右,因为要把转换后的左子树链接到根节点的右子树上,因此进入递归之后要先把节点的右子树保存下来,然后进入左子树,左子树转换后应该返回最后一个訪问的节点.这个节点的后继是根节点的转换后右子树.说起来很绕,可能看代码反而好一些. 注意一个问题是,不管如何.转换后的根节点一定要把左子树置空.要么会报错的. TreeNode* preOrder(TreeNode *root){ if(!root||(!root->left&&!…
题目 给定一个二叉树,原地将它展开为链表. 例如,给定二叉树 1 / \ 2 5 / \ \ 3 4 6 将其展开为: 1 \ 2 \ 3 \ 4 \ 5 \ 6 解析 通过递归实现:可以用先序遍历,然后串成链表 主要思想就是:先递归对右子树进行链表化并记录,然后将root->right指向 左子树进行链表化后的头结点,然后一直向右遍历子树,连接上之前的右子树 /** * Definition for a binary tree node. * struct TreeNode { * int v…
Flatten Binary Tree to Linked List: Given a binary tree, flatten it to a linked list in-place. For example, Given 1 / \ 2 5 / \ \ 3 4 6 The flattened tree should look like: 1 \ 2 \ 3 \ 4 \ 5 \ 6 这题的主要难点是"in-place".因为这个flatten的顺序是中.左.右(相当于中序遍历),所…
114. Flatten Binary Tree to Linked List (Medium) 453. Flatten Binary Tree to Linked List (Easy) 解法1: 用stack. class Solution { public: void flatten(TreeNode *root) { if(!root) return; TreeNode *pnode = NULL; stack<TreeNode*> s; s.push(root); while(!s…