leetcode 树类型题

树的测试框架:

 1 // leetcodeTree.cpp : 定义控制台应用程序的入口点。
 2 //
 3 
 4 #include "stdafx.h"
 5 #include <iostream>
 6 #include <queue>
 7 #include <stack>
 8 #include <vector>
 9 
10 using namespace std;
11 
12 struct TreeNode {
13     int val;
14     TreeNode *left;
15     TreeNode *right;
16     TreeNode(int x) : val(x), left(nullptr), right(nullptr) { };
17 };
18 struct TreeLinkNode {
19     int val;
20     TreeLinkNode *left;
21     TreeLinkNode *right;
22     TreeLinkNode *next;
23     TreeLinkNode(int x) : val(x) { left = nullptr; right = nullptr; next = nullptr; };
24 };
25 
26 TreeNode* build(TreeNode *root, int val) {  // 构造一棵树
27     if (root == nullptr) {
28         root = new TreeNode(val);
29         return root;
30     }
31     if (val < root->val)
32         root->left = build(root->left, val);
33     else
34         root->right = build(root->right, val);
35 
36     return root;
37 }
38 
39 vector<int> preOrderTraversal(TreeNode *root) {  // 非递归先序遍历
40     vector<int> result;
41     stack<TreeNode*> stk;
42     if (root != nullptr)
43         stk.push(root);
44     while (!stk.empty()) {
45         TreeNode *p = stk.top();
46         stk.pop();
47         cout << '\t' << p->val;       // 打印遍历序列 
48         result.push_back(p->val);
49 
50         if (p->right != nullptr)       // 注意是先进栈右孩子,再进栈左孩子
51             stk.push(p->right);
52         if (p->left != nullptr)
53             stk.push(p->left);
54     }
55     return result;
56 }
57 
58 int main() {
59     int t[] = {5,4,3,6,7};
60     TreeNode* root = nullptr;
61     for(int i=0;i<sizeof(t)/sizeof(int);++i)  // build a tree
62         build(root,t[i]);
63         
64     preOrderTraversal(root);
65     
66     return 0; 
67 }
测试框架

1,Binary Tree Preorder Traversal(非递归)

 1 vector<int> preOrderTraversal(TreeNode *root) {  // 非递归先序遍历
 2     vector<int> result;
 3     stack<TreeNode*> stk;
 4     if (root != nullptr)
 5         stk.push(root);
 6     while (!stk.empty()) {
 7         TreeNode *p = stk.top();
 8         stk.pop();
 9         cout << '\t' << p->val;
10         result.push_back(p->val);
11 
12         if (p->right != nullptr)       // 注意是先进栈右孩子,再进栈左孩子
13             stk.push(p->right);
14         if (p->left != nullptr)
15             stk.push(p->left);
16     }
17     return result;
18 }
preOrderTraversal

2,Binary Tree Inorder Traversal(非递归)

 1 vector<int> inOrderTraversal(TreeNode *root) {  // 非递归中序遍历
 2     vector<int> result;
 3     stack<TreeNode*> stk;
 4     TreeNode *p = root;
 5 
 6     while (!stk.empty() || p != nullptr) {
 7         if (p != nullptr) {
 8             stk.push(p);
 9             p = p->left;
10         }
11         else {
12             p = stk.top();
13             stk.pop();
14             cout << '\t' << p->val;
15             result.push_back(p->val);
16             p = p->right;
17         }
18     }
19     return result;
20 }
inOrderTraversal

3,Binary Tree Postorder Traversal(非递归)

 1 vector<int> postOrderTravelsal(TreeNode *root) {
 2     vector<int> result;
 3     stack<TreeNode*> stk;
 4     if (root == nullptr)
 5         return result;
 6 
 7     TreeNode *pCur, *pLastVisit;
 8     pCur = root;
 9     pLastVisit = nullptr;
10 
11     while (pCur) {          // 把 pCur 移动到最左下方
12         stk.push(pCur);
13         pCur = pCur->left;   
14     }
15     while (!stk.empty()) {
16         pCur = stk.top();
17         stk.pop();
18         if (pCur->right == nullptr || pCur->right == pLastVisit) {  // 如果当前节点无右子树或者右子树已经被访问过,则访问
19             result.push_back(pCur->val);
20             cout << '\t' << pCur->val;
21             pLastVisit = pCur;
22         }
23         else {  // 跳到右子树去
24             stk.push(pCur);  // 根节点再次入栈
25             pCur = pCur->right;
26             while (pCur) {
27                 stk.push(pCur);
28                 pCur = pCur->left;
29             }
30         }
31     }
32     cout << endl;
33     return result;
34 }
postOrderTravelsal

4,Binary Tree Level Order Traversal(不区分层)

 1 void levelOrderI(TreeNode* root) {  // 层次遍历,不分层次
 2     if (root == nullptr)
 3         return;
 4     queue<TreeNode*> q;
 5     q.push(root);
 6     while (!q.empty()) {
 7         TreeNode *temp = q.front();
 8         q.pop();
 9         cout << temp->val << '\t';
10         if (temp->left)
11             q.push(temp->left);
12         if (temp->right)
13             q.push(temp->right);
14     }
15     cout << endl;
16 }
levelOrder

5,Binary Tree Level Order Traversal(区分层次)

 1 vector<vector<int>> levelOrderII1(TreeNode* root) { // 迭代版
 2     vector<vector<int>> result;
 3     queue<TreeNode*> current, next;
 4 
 5     if (root == nullptr)
 6         return result;
 7     else
 8         current.push(root);
 9 
10     while (!current.empty()) {
11         vector<int> level;  // elements in one level
12         while (!current.empty()) {
13             TreeNode *node = current.front();
14             current.pop();
15             level.push_back(node->val);
16             if (node->left)
17                 next.push(node->left);
18             if (node->right)
19                 next.push(node->right);
20         }
21         result.push_back(level);
22         swap(current, next);
23     }
24     return result;
25 }
26 
27 
28 void traverse(TreeNode *root, size_t level, vector<vector<int>>& result) {
29     if (!root)
30         return;
31     if (level > result.size())
32         result.push_back(vector<int>());  // 如果层数不够,新加一层来存储
33 
34     result[level - 1].push_back(root->val);
35     traverse(root->left, level + 1, result);
36     traverse(root->right, level + 1, result);
37 }
38 vector<vector<int>> levelOrderII2(TreeNode* root) {   // 递归版
39     vector<vector<int>> result;
40     traverse(root, 1, result);
41     return result;
42 }
levelOrder(分层)

6,Binary Tree Level Order Traversal(分层,从下向上)

 1 vector<vector<int>> levelOrderBottomI(TreeNode *root) {  // 递归版
 2     vector<vector<int>> result;
 3     traverse(root, 1, result);
 4     reverse(result.begin(), result.end());   // 多了这一行,调用相同的函数
 5     return result;
 6 }
 7 
 8 vector<vector<int>> levelOrderBottomII(TreeNode *root) {
 9     vector<vector<int>> result;
10     if (root == nullptr)
11         return result;
12 
13     queue<TreeNode*> current, next;
14 
15     current.push(root);
16     while (!current.empty()) {
17         vector<int> level;  // elments in one level
18         while (!current.empty()) {
19             TreeNode *node = current.front();
20             current.pop();
21             level.push_back(node->val);
22             if (node->left)
23                 next.push(node->left);
24             if (node->right)
25                 next.push(node->right);
26         }
27         result.push_back(level);
28         swap(next, current);
29     }
30     reverse(result.begin(), result.end());  // 多了这一行
31     return result;
32 }
levelOrderBottom

7,Binary Tree Zigzag Level Order Traversal

 1 void traverse(TreeNode *root, size_t level, vector <vector<int>>& result, bool left_to_right) { // 递归往返方向
 2     if (!root)
 3         return;
 4     if (level > result.size())
 5         result.push_back(vector<int>());
 6     if (left_to_right)
 7         result[level - 1].push_back(root->val);
 8     else
 9         result[level - 1].insert(result[level - 1].begin(), root->val);
10     traverse(root->left, level + 1, result, !left_to_right);
11     traverse(root->right, level + 1, result, !left_to_right);
12 }
13 vector<vector<int>> zigzagLevelOrderI(TreeNode *root) {
14     vector<vector<int>> result;
15     traverse(root, 1, result, true);
16     return result;
17 }
18 
19 vector<vector<int>> zigzagLevelOrderII(TreeNode *root) {  // 迭代版
20     vector<vector<int>> result;
21     queue<TreeNode*> current, next;
22     bool left_to_right = true;
23     if (root == nullptr)
24         return result;
25     else
26         current.push(root);
27     while (!current.empty()) {
28         vector<int> level;     // elements in one level
29         while (!current.empty()) {
30             TreeNode *node = current.front();
31             current.pop();
32             level.push_back(node->val);
33             if (node->left)
34                 next.push(node->left);
35             if (node->right)
36                 next.push(node->right);
37         }
38         if (!left_to_right)                       // 多加了这一行
39             reverse(level.begin(),level.end());
40         result.push_back(level);
41         left_to_right = !left_to_right;
42         swap(next, current);
43     }
44     return result;
45 }
46 zigzagLevelOrder
zigzagLevelOrder

8,Recover Binary Search Tree

 1 void inorder(TreeNode* root, vector<TreeNode*>& list, vector<int>& vals) {
 2     if (root == nullptr) return;
 3     inorder(root->left, list, vals);
 4     list.push_back(root);
 5     vals.push_back(root->val);
 6     inorder(root->right, list, vals);
 7 }
 8 void recoverBSTTree(TreeNode* root) {
 9     vector<TreeNode*> list;
10     vector<int> vals;
11     sort(vals.begin(), vals.end());
12     for (size_t i = 0; i < list.size(); ++i) {
13         list[i]->val = vals[i];
14     }
15 }
recoverBSTTree

9,Same Tree

 1 bool isSameTreeI(TreeNode *p, TreeNode *q) {  // 递归版
 2     if (!p && !q)
 3         return true;
 4     if (!p || !q)
 5         return false;
 6 
 7     return p->val == q->val && isSameTreeI(p->left, q->left) && isSameTreeI(p->right, q->right);
 8 }
 9 
10 bool isSampleTreeII(TreeNode *p, TreeNode *q) {  // 迭代
11     stack<TreeNode*> stk;
12     stk.push(p);
13     stk.push(q);
14 
15     while (!stk.empty()) {
16         p = stk.top();
17         stk.pop();
18         q = stk.top();
19         stk.pop();
20         
21         if (!q && !q)
22             continue;
23         if (!q || !p)
24             return false;
25         if (q->val != p->val)
26             return false;
27 
28         stk.push(p->right);
29         stk.push(q->right);
30 
31         stk.push(p->left);
32         stk.push(q->left);
33     }
34     return true;
35 }
isSameTree

10,Symmetric Tree(对称树)

 1 bool isSymmetricI(TreeNode *p, TreeNode *q) {  // 迭代版本
 2     if (!p && !q)
 3         return true;
 4     if (!p || !q)
 5         return false;
 6     return p->val == q->val && isSymmetricI(p->left, q->left) && isSymmetricI(p->right, q->left);
 7 }
 8 bool isSymmetricI(TreeNode *root) {
 9     if (root == nullptr) return true;
10     return isSymmetricI(root->left, root->right);
11 }
12 
13 
14 bool isSymmetricII(TreeNode *root) {  // 迭代版
15     if (!root) return true;
16     stack<TreeNode*> stk;
17     stk.push(root->left);
18     stk.push(root->right);
19 
20     while (!stk.empty()) {
21         auto p = stk.top();
22         stk.pop();
23         auto q = stk.top();
24         stk.pop();
25 
26         if (!p && !p) continue;
27         if (!p || !q) return false;
28         if (p->val != q->val) return false;
29 
30         stk.push(p->left);
31         stk.push(q->right);
32 
33         stk.push(p->right);
34         stk.push(q->left);
35     }
36     return true;
37 }
isSymmetric

11,Balanced Binary Tree

 1 int balancedHeight(TreeNode *root) {
 2     if (root == nullptr)
 3         return 0;   // 终止条件
 4 
 5     int leftHeight = balancedHeight(root->left);
 6     int rightHeight = balancedHeight(root->right);
 7 
 8     if (leftHeight < 0 || rightHeight < 0 || abs(leftHeight - rightHeight) > 1)   // 什么时候 leftHight 会小于 0?
 9         return -1;   // 剪枝
10 
11     return max(leftHeight, rightHeight) + 1;
12 
13 }
14 bool isBalanceTree(TreeNode *root) {
15     return balancedHeight(root) >= 0;
16 }
isBalanceTree

12,Flatten Binary Tree to Linked List

 1 void flatten(TreeNode *root) {  // 迭代版,先序遍历然后组成单链表形状
 2     if (root == nullptr)
 3         return;
 4     stack<TreeNode*> stk;
 5     stk.push(root);
 6     TreeNode dummy(-1);
 7     TreeNode *prev = &dummy;
 8 
 9     while (!stk.empty()) {
10         TreeNode *node = stk.top();
11         stk.pop();
12 
13         if (node->right)
14             stk.push(node->right);
15         if (node->left)
16             stk.push(node->left);
17 
18         node->left = nullptr;
19         prev->right = node;
20         prev = prev->right;
21     }
22     root = dummy.right;
23 }
flatten

13,Populating Next Right Pointers in Each Node(II)

 1 void connectI(TreeLinkNode *root) {  // 迭代版
 2     while (root) {
 3         TreeLinkNode *next = nullptr;  // the first node of next level
 4         TreeLinkNode *prev = nullptr; //   previous node on the same level
 5         while (root) {  // 对于每一行来说
 6             if (!next)
 7                 next = root->left ? root->left : root->right;
 8 
 9             if (root->left) {
10                 if (prev)
11                     prev->next = root->left;
12                 prev = root->left;
13             }
14             if (root->right) {
15                 if (prev)
16                     prev->next = root->right;
17                 prev = root->right;
18             }
19             root = root->next;
20         }
21         root = next;   // turn to next level
22     }
23 }
24 
25 
26 void connectII(TreeLinkNode *root) {  // 迭代版
27     if (root == nullptr) return;
28 
29     TreeLinkNode dummy(-1);
30     for (TreeLinkNode *curr = root, *prev = &dummy; curr; curr = curr->next) {
31         if (curr->left) {
32             prev->next = curr->left;
33             prev = prev->next;
34         }
35         if (curr->right) {
36             prev->next = curr->right;
37             prev = prev->next;
38         }
39     }
40     connectII(dummy.next);   // 下一层的第一个节点
41 }
42 
43 connect
connect

14,Construct Binary Tree from Preorder and Inorder Traversal

 1 TreeNode* buildTreeI(vector<int>::iterator pre_first, vector<int>::iterator pre_last,
 2     vector<int>::iterator in_first, vector<int>::iterator in_last) {
 3     if (pre_first == pre_last)  // 如果 左子树为空,结束
 4         return nullptr;
 5     if (in_first == in_last)    // 如果 右子树为空,结束
 6         return nullptr;
 7 
 8     auto root = new TreeNode(*pre_first);
 9     auto inRootPos = find(in_first, in_last, *pre_first);
10     int leftSize = distance(in_first, inRootPos);
11 
12     root->left = buildTreeI(next(pre_first), next(pre_first, leftSize + 1),in_first,next(in_first,leftSize));
13     root->right = buildTreeI(next(pre_first, leftSize + 1), pre_last, next(inRootPos), in_last);
14 
15     return root;
16 }
17 TreeNode* buildTreeI(vector<int>& preOrder, vector<int>& inOrder) {  // 根据先序遍历和中序遍历序列构造二叉树
18     return buildTreeI(begin(preOrder), end(preOrder), begin(inOrder), end(inOrder));
19 }
buildTree

15,Construct Binary Tree from Inorder and Postorder Traversal

 1 TreeNode* buildTreeII(vector<int>::iterator in_first, vector<int>::iterator in_last,
 2     vector<int>::iterator post_first, vector<int>::iterator post_last) {
 3 
 4     if (in_first == in_last)
 5         return nullptr;
 6     if (post_first == post_last)
 7         return nullptr;
 8 
 9     int pRootValue = *prev(post_last);
10     TreeNode* root = new TreeNode(pRootValue);
11 
12     auto inRootPos = find(in_first, in_last, pRootValue);
13     int leftSize = distance(in_first, inRootPos);
14 
15     root->left = buildTreeII(in_first, inRootPos, post_first, next(post_first, leftSize));  // 注意迭代器“前闭后开”原则
16     root->right = buildTreeII(next(inRootPos), in_last, next(post_first, leftSize), prev(post_last));
17 
18     return root;
19 }
20 TreeNode* buildTreeII(vector<int>& inOrder, vector<int>& postOrder) {
21     return buildTreeII(begin(inOrder), end(inOrder), begin(postOrder), end(postOrder));
22 }
buildTree

16,Unique Binary Search Trees

 1 int numTrees(int n) {  // 一维动态规划
 2     vector<int> f(n + 1, 0);
 3 
 4     f[0] = 1;
 5     f[1] = 1;
 6     for (int i = 2; i <= n; ++i) {
 7         for (int k = 1; k <= i; ++k)
 8             f[i] += f[k - 1] * f[i - k];
 9     }
10     return f[n];
11 }
numTrees

 17,Unique Binary Search Trees II

 1 vector<TreeNode*> generate(int start, int end) {  // 还未看懂
 2     vector<TreeNode*> subTree;
 3     if (start > end) {
 4         subTree.push_back(nullptr);
 5         return subTree;
 6     }
 7     for (int k = start; k <= end; ++k) {  //对每一个节点
 8         vector<TreeNode*> leftSubs = generate(start, k - 1);
 9         vector<TreeNode*> rightSubs = generate(k + 1, end);
10         for (auto i : leftSubs) {
11             for (auto j : rightSubs) {
12                 TreeNode* node = new TreeNode(k);
13                 node->left = i;
14                 node->right = j;
15                 subTree.push_back(node);
16             }
17         }
18     }
19     return subTree;
20 }
21 vector<TreeNode*> generateTrees(int n) {
22     if (n == 0) return generate(1, 0);
23     return generate(1, n);
24 }
generate

18,Vaildate Binary Search Tree

1 bool isVaildBST(TreeNode* root, int low, int hight) {
2     if (root == nullptr) return true;
3     return root->val > low && root->val < hight
4         && isVaildBST(root->left, low, root->val)
5         && isVaildBST(root->right, root->val, hight);
6 }
7 bool isVaildBST(TreeNode* root) {
8     return isVaildBST(root, INT_MIN, INT_MAX);
9 }
isVaildBST

19,Convert Sorted Array to Binary Search Tree

 1 TreeNode* sortedArrayToBST(vector<int>::iterator first, vector<int>::iterator last) {
 2     int length = distance(first, last);
 3     if (length <= 0) return nullptr;
 4     auto mid = first + length / 2;
 5     TreeNode* root = new TreeNode(*mid);
 6     root->left = sortedArrayToBST(first, mid);
 7     root->right = sortedArrayToBST(mid + 1, last);
 8 
 9     return root;
10 }
11 TreeNode* sortedArrayToBST(vector<int>& nums) {
12     return sortedArrayToBST(nums.begin(), nums.end());
13 }
sortedArrayToBST

20,Convert Sorted List to Binary Search Tree

 1 TreeNode* helper(ListNode* head, ListNode* tail) {
 2     if (head == tail) return nullptr;
 3     ListNode* slow = head, *fast = head;
 4     while (fast->next != tail && fast->next->next != tail) {
 5         slow = slow->next;
 6         fast = fast->next->next;
 7     }
 8     TreeNode* cur = new TreeNode(slow->val);
 9     cur->left = helper(head, slow);
10     cur->right = helper(slow->next, tail);
11 
12     return cur;
13 }
14 TreeNode* sortedListToBST(ListNode* head) {
15     if (!head) return nullptr;
16     return helper(head, nullptr);
17 }
18 
19 TreeNode* sortedListToBST1(ListNode* head) {  // 递归
20     if (!head) return nullptr;
21     if (!head->next) return new TreeNode(head->val);
22     ListNode *slow = head, *fast = head, *last = head;
23     while (fast->next && fast->next->next) {
24         last = slow;
25         slow = slow->next;
26         fast = fast->next->next;
27     }
28     fast = slow->next;  // slow 指向中间元素的节点,fast 指向下一个链表的起始
29     last->next = nullptr;  // last == slow 将要作为根节点
30     TreeNode * cur = new TreeNode(slow->val);
31     if (head != slow)  // 此处需要加以判断,否则当左边只有一个节点的时候会出错
32         cur->left = sortedListToBST1(head);
33     cur->right = sortedListToBST1(fast);
34 
35     return cur;
36 }
sortedListToBST

21,Minimum Depth of Binary Tree

 1 int minDepth(TreeNode* root) { // 递归版
 2     if (!root) return 0;
 3     if (!root->left) return 1 + minDepth(root->right);
 4     if (!root->right) return 1 + minDepth(root->left);
 5     return 1 + min(minDepth(root->left), minDepth(root->right));
 6 }
 7 
 8 int minDepthII(TreeNode* root) {  // 层次遍历,记录层次
 9     if (!root) return 0;
10     int minLevel = 0;
11     queue<TreeNode*> q;
12     q.push(root);
13     while (!q.empty()) {
14         ++minLevel;
15         int size = q.size();
16         for (int i = 0; i < size; ++i) {
17             auto cur = q.front();
18             q.pop();
19             if (!cur->left && !cur->right)
20                 return minLevel;
21             if (cur->left)
22                 q.push(cur->left);
23             if (cur->right)
24                 q.push(cur->right);
25         }
26     }
27     return -1;
28 }
minDepth

22,Maximum Depth of Binary Tree

 1 int maxDepth(TreeNode* root) {  // 递归版
 2     if (root == nullptr)
 3         return 0;
 4     int leftHeight = maxDepth(root->left);
 5     int rightHeight = maxDepth(root->right);
 6     return 1 + max(leftHeight, rightHeight);
 7 }
 8 
 9 
10 int maxDepthII(TreeNode* root) { // 迭代版,通过层次遍历来实现
11     if (root == nullptr)
12         return 0;
13     queue<TreeNode*> current, next;
14     int level = 0;
15     current.push(root);
16     while (!current.empty()) {  // 进入每一层
17         ++level;
18         while (!current.empty()) {  // 对每一层的每个节点
19             TreeNode* node = current.front();
20             current.pop();
21             if (node->left)
22                 next.push(node->left);
23             if (node->right)
24                 next.push(node->right);
25         }
26         swap(current, next); // 进入下一层
27     }
28     return level;
29 }
maxDepth

23,Path Sum

1 bool hasPathSum(TreeNode* root, int sum) {  //递归版
2     if (!root) return false;
3     if (!root->left && !root->right)  // 到了叶子节点,进行判断
4         return sum == root->val;
5     return hasPathSum(root->left, sum - root->val) 
6         || hasPathSum(root->right, sum - root->val);
7 }
hasPathSum

24,Path Sum II

 1 void pathSum(TreeNode* root, int gap, vector<int>& curr, vector<vector<int>>& result) {
 2     if (root == nullptr) return;
 3 
 4     curr.push_back(root->val);
 5 
 6     if (!root->left && !root->right) {  // leaf
 7         if (gap == root->val)
 8             result.push_back(curr);
 9     }
10     pathSum(root->left, gap - root->val, curr, result);
11     pathSum(root->right, gap - root->val, curr, result);
12     curr.pop_back();  // 如果到叶子节点,发现不相等,则回退到叶子节点的父节点,并弹出该叶子节点的 val
13 }
14 vector<vector<int>> pathSum(TreeNode* root, int sum) {
15     vector<vector<int>> result;
16     vector<int> curr; // 中间结果
17     pathSum(root, sum, curr, result);
18     return result;
19 }
pathSum

25,Binary Tree Maximum Path Sum

 1 int max_sum = INT_MIN;
 2 int dfs(TreeNode* root) {
 3     if (root == nullptr) return 0;
 4     int l = dfs(root->left);
 5     int r = dfs(root->right);
 6     int sum = root->val;
 7     if (l > 0) sum += l;
 8     if (r > 0) sum += r;
 9     max_sum = max(max_sum, sum);
10     return max(r, l) > 0 ? max(r, l) + root->val : root->val;
11 }
12 int maxPathSum(TreeNode* root) {  //还未看懂
13     max_sum = INT_MIN;
14     dfs(root);
15     return max_sum;
16 }
maxPathSum

26,Populating Next Right Pointers in Each Node

1 // 题目同 13,Populating Next Right Pointers in Each Node(II)
connect

27,Sum Root to Leaf Numbers

 1 int dfs(TreeNode* root, int sum) {
 2     if (root == nullptr) return 0;
 3     if (root->left == nullptr && root->right == nullptr)
 4         return sum * 10 + root->val;
 5     return dfs(root->left, sum * 10 + root->val) +
 6         dfs(root->right, sum * 10 + root->val);
 7 }
 8 int sumNumbers(TreeNode* root) {
 9     return dfs(root, 0);
10 }
sumNumbers

 =============补充=========

 1,求两个节点的最近公共祖先节点

 1 // 求树中任意两个节点的最近公共祖先
 2 // 获取树中节点的路径
 3 bool getNodePath(TreeNode* root, stack<TreeNode*>&stk, TreeNode* p) {  // 把路径存入 stk 中,根节点先入栈
 4     if (root == nullptr)
 5         return false;  // 递归出口
 6     stk.push(root);
 7 
 8     if (root->val == p->val)
 9         return true;
10     bool left = getNodePath(root->left, stk, p);
11     if (left)                           // 从左子树找到了
12         return true;
13     bool right = getNodePath(root->right, stk, p);
14     if (right)                        // 从右子树找到了
15         return true;
16     stk.pop();                    //回溯
17     return false;
18 }
19 
20 // method 1 : the tree is BST
21 TreeNode* getCommonAncestorI(TreeNode* root, TreeNode*p, TreeNode*q) {
22     if (root == nullptr)
23         return nullptr;
24     else if (p->val >= root->val && q->val <= root->val
25         || p->val <= root->val && q->val >= root->val)  // 设此 BST 不允许有重复值
26         return root;
27     else if (p->val < root->val && q->val < root->val)
28         getCommonAncestorI(root->left, p, q);
29     else if (p->val > root->val && q->val > root->val)
30         getCommonAncestorI(root->right, p, q);
31 }
32 
33 // method 2 : the tree is triple_link tree(point to parent)
34 TriTreeNode* getCommonAncestorII(TriTreeNode* root, TriTreeNode* p, TriTreeNode* q) { // 同解法 I
35     stack<TriTreeNode*> stk1;
36     stack<TriTreeNode*> stk2;
37     TriTreeNode* pCurr = p;
38     TriTreeNode* qCurr = q;
39     while (pCurr) {
40         if (pCurr == q)
41             return pCurr;
42         else
43             stk1.push(pCurr);
44         pCurr = pCurr->parent;
45     }
46     while (qCurr) {
47         if (qCurr == p)
48             return qCurr;
49         else
50             stk2.push(qCurr);
51         qCurr = qCurr->parent;
52     }
53     // 从根节点出栈,比较,最近的公共节点是最后一个相等的出栈元素
54     TriTreeNode* node = nullptr;
55     while (!stk1.empty() && !stk2.empty()) {
56         if (stk1.top() == stk2.top()) {
57             node = stk1.top();
58         }
59         else {
60             return node;
61         }
62         stk1.pop();
63         stk2.pop();
64     }
65     return node;
66 }
67 
68 // mothod 3 : the tree is oridinary binary tree
69 // 首先存储两个节点了路径,然后类似方式 II 进行比较
70 TreeNode* getCommonAncestorIII(TreeNode* root, TreeNode*p, TreeNode*q) {
71     stack<TreeNode*> stk1;
72     stack<TreeNode*> stk2;
73     getNodePath(root, stk1,p);
74     getNodePath(root, stk2, q);
75 
76     TreeNode* node = nullptr;
77     int size1 = stk1.size();
78     int size2 = stk2.size();
79     int n = abs(size1 - size2);
80     for (int i = 0; i < n; ++i) {  // 保证两条链一样长
81         if (size1 > size2)
82             stk1.pop();
83         else
84             stk2.pop();
85     }
86     while (!stk1.empty() && !stk2.empty()) { // 寻找最近的父节点
87         if (stk1.top() == stk2.top())
88             return stk1.top();
89         else
90             stk1.pop();
91             stk2.pop();
92     }
93     return stk1.top();
94 }
getCommonAncestor

 

以上题目均来源于:https://www.github.com/soulmachine/leetcode(leetcode-cpp.pdf)

note:补充部分题目不来源于此书

posted on 2019-03-06 21:29  爱笑的张飞  阅读(239)  评论(0编辑  收藏  举报

导航