day18
1.剑指 Offer 55 - I. 二叉树的深度
1)dfs 取左、右子树高度的最大值
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 int maxDepth(TreeNode* root) { 13 if(root == nullptr) return 0; 14 if(root -> left == nullptr && root -> right == nullptr) return 1; //这一行可加可不加 15 return max(maxDepth(root -> left) + 1,maxDepth(root -> right) + 1); 16 } 17 };
2)bfs 层序遍历整棵树,看有多少层
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 int maxDepth(TreeNode* root) { 13 if(root == nullptr) return 0; 14 queue<TreeNode*> q; 15 q.push(root); 16 int res = 0; 17 while(!q.empty()){ 18 res ++; 19 int n = q.size(); 20 for(int i = 0;i < n;i ++){ 21 TreeNode* tmp = q.front(); 22 q.pop(); 23 if(tmp -> left) q.push(tmp -> left); 24 if(tmp -> right) q.push(tmp -> right); 25 } 26 } 27 return res; 28 } 29 };
贴一个K神的层序遍历(用的vector)
1 class Solution { 2 public: 3 int maxDepth(TreeNode* root) { 4 if(root == nullptr) return 0; 5 vector<TreeNode*> que; 6 que.push_back(root); 7 int res = 0; 8 while(!que.empty()) { 9 vector<TreeNode*> tmp; 10 for(TreeNode* node : que) { 11 if(node->left != nullptr) tmp.push_back(node->left); 12 if(node->right != nullptr) tmp.push_back(node->right); 13 } 14 que = tmp; 15 res++; 16 } 17 return res; 18 } 19 };
2.剑指 Offer 55 - II. 平衡二叉树
自顶而下,未剪枝(不推荐,时间复杂度过高)
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 bool isBalanced(TreeNode* root) { 13 if(root == nullptr) return true; 14 if(abs(Height(root -> left) - Height(root -> right)) > 1) return false; 15 return isBalanced(root -> left) && isBalanced(root -> right); 16 } 17 18 int Height(TreeNode* root){ 19 if(root == nullptr) return 0; 20 return max(Height(root -> left),Height(root -> right)) + 1; 21 } 22 };
后序遍历,剪枝(推荐)
从底端开始,如果recur返回的结果为-1就说明某个节点的左右子树深度相差超过了1(不是平衡二叉树),只要发现一个就可以一直返回-1了;反之recur返回的结果不是-1则这个节点及其左右子树构成的二叉树分支是平衡二叉树,返回这个分支二叉树的高度即可(其父节点只要在这个返回的高度+1即可,避免了自顶而下的重复计算)
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 bool isBalanced(TreeNode* root) { 13 return recur(root) != -1; 14 } 15 16 int recur(TreeNode* root){ 17 if(root == nullptr) return 0; 18 int hl = recur(root -> left); 19 if(hl == -1) return -1; 20 int hr = recur(root -> right); 21 if(hr == -1) return -1; 22 if(abs(hl - hr) > 1) return -1; 23 return max(hl,hr) + 1; 24 } 25 };

浙公网安备 33010602011771号