二叉树相关面试的集锦(一)
一、第K层节点个数
template<class T> int BinaryTree<T>::_K_LevelAmount(Node* root, int K) { if (root == NULL) { return 0; } if (K == 1) { return 1; } return _K_LevelAmount_Update(root->_LeftChild, K - 1) + _K_LevelAmount_Update(root->_RightChild, K - 1); }
二、二叉树中节点的路径
1.递归方式
2.非递归方式
/*递归*/
template<class T> bool BinaryTree<T>::_FindPathWithRecursion(Node* root, Node* node, vector<Node*>& Vector) { if (root == NULL) { return false; } Vector.push_back(root); if (root == node) { return true; } else { bool IsFound = _FindPathWithRecursion(root->_LeftChild, node, Vector) || _FindPathWithRecursion(root->_RightChild, node, Vector); if (!IsFound) { Vector.pop_back(); } return IsFound; } }
/*非递归*/ template<class T> bool BinaryTree<T>::_FindPath(Node* root, Node* node, vector<Node*>& Vector) { Node* cur = root; Node* prev = NULL; if (root) { while (cur || !Vector.empty()) { while (cur) { Vector.push_back(cur); if (cur == node) { return true; } cur = cur->_LeftChild; } cur = Vector.back(); //////////////// Node* cur = Vector.back(); 犯过的错误 if (cur->_RightChild == NULL || cur->_RightChild == prev) { Vector.pop_back(); prev = cur; cur = NULL; //不用再向左走了 } else { cur = cur->_RightChild; } } } return false; }
/*为什么只能用后序非递归的原因*/
三、两个节点的最近公共节点
方法一:
找出两个节点的路径,最后一个匹配上的节点就是最近公共祖先节点
template<class T> BinaryTreeNode<T>* BinaryTree<T>::_Ancestor(Node* node1, Node* node2) { vector<Node*> Vector1, Vector2; Node* cur = NULL; if (_FindPath(_root, node1, Vector1) && _FindPath(_root, node2, Vector2)) { for (int i = 0; i < Vector1.size() && i < Vector2.size(); ++i) { if (Vector1[i] == Vector2[i]) cur = Vector1[i]; } } return cur; }
方法二:
/** * 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* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { bool PrevTag = false; return LowestCommonAncestor(root,p,q,PrevTag); } TreeNode* LowestCommonAncestor(TreeNode* root,TreeNode* p,TreeNode* q,bool& PrevTag) { if(root) { bool LeftTag = false,RightTag = false; TreeNode* Left = LowestCommonAncestor(root->left,p,q,LeftTag); if(Left) return Left; TreeNode* Right = LowestCommonAncestor(root->right,p,q,RightTag); if(Right) return Right; if(root == p || root == q) PrevTag = true; if(LeftTag && RightTag) return root; else if(LeftTag || RightTag) { if(PrevTag) return root; PrevTag = true; } return NULL; } return NULL; } };