OJ连接:https://leetcode-cn.com/problems/er-cha-shu-de-shen-du-lcof/submissions/html
当前树的深度 = max(左子树深度,右子树深度)+1,因此要求当前树的深度得先递归求出左子树深度和右子树深度。要求出左右子树的深度一样的道理,再往下递归,直到遇到空树,深度直接返回0。node
/** * 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: int maxDepth(TreeNode* root) { if(root == NULL) return 0; int leftDepth = maxDepth(root->left); int rightDepth = maxDepth(root->right); return leftDepth > rightDepth ? leftDepth+1 : rightDepth+1; } };
OJ连接:https://leetcode-cn.com/problems/balanced-binary-tree/c++
什么是高度平衡二叉树?一颗二叉树的左右子树的高度差不超过1,且树中的全部子树都知足这个条件,则称这颗二叉树是高度平衡二叉树。web
那么要判断一颗二叉树是不是平衡二叉树能够分为3步:面试
/** * 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: int maxDepth(TreeNode* root) { if(root == NULL) return 0; int leftDepth = maxDepth(root->left); int rightDepth = maxDepth(root->right); return leftDepth > rightDepth ? leftDepth+1 : rightDepth+1; } bool isBalanced(TreeNode* root) { if(root == NULL) return true; int leftDepth = maxDepth(root->left); int rightDepth = maxDepth(root->right); return abs(leftDepth-rightDepth) < 2 && isBalanced(root->left) && isBalanced(root->right); } };
OJ连接:https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/数据结构
/** * 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: TreeNode* _buildTree(vector<int>& preorder, vector<int>& inorder, int& prei, int inbegin, int inend) { if(inbegin > inend) return nullptr; int rootVal = preorder[prei]; TreeNode* root = new TreeNode(rootVal); // 在中序序列中去找root的位置 int inRooti = inbegin; while(inRooti <= inend) { if(inorder[inRooti] == rootVal) break; else ++inRooti; } // [inbegin, inRooti-1] inRooti [inRooti+1, inend] 左子树的中序[inbegin, inRooti-1] 右子树的中序[inRooti+1, inend] // 若是中序左区间存在则递归建立左子树,若是中序左区间不存在,则左子树是空树 if(inbegin <= inRooti-1) root->left = _buildTree(preorder, inorder, ++prei, inbegin, inRooti-1); else root->left= nullptr; // 同上 if(inRooti+1 <= inend) root->right = _buildTree(preorder, inorder, ++prei, inRooti+1, inend); else root->right = nullptr; return root; } TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) { int prei = 0; int inbegin = 0; int inend = inorder.size()-1; return _buildTree(preorder, inorder, prei, inbegin, inend); } };
若是你有不是很明白的地方,这里有讲解视频哦:ide
数据结构高频面试题之二叉树(上)(C++实现)svg
或者点击连接观看:单击连接就能够了ui
数据结构面试题及答案解析系列若是对你有帮助,请点赞,转发,鼓励博主继续更新下去哦.net
上一篇:http://www.javashuo.com/article/p-nyydtwso-mv.html
下一篇:http://www.javashuo.com/article/p-ygpqqfpk-mr.html