zoukankan      html  css  js  c++  java
  • leetcode236 二叉树的最近公共祖先

    思路:

    后序遍历。

    实现:

     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 {
    12 public:
    13     TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q)
    14     {
    15         if (root == NULL or root == p or root == q) return root;
    16         TreeNode* l = lowestCommonAncestor(root->left, p, q);
    17         TreeNode* r = lowestCommonAncestor(root->right, p, q); 
    18         if (l == p)
    19         {
    20             if (r == q) return root;
    21             else return l;
    22         }
    23         else if (l == q)
    24         {
    25             if (r == p) return root;
    26             else return l;
    27         }
    28         else if (l == NULL) return r;
    29         else return l;
    30     }
    31 };
  • 相关阅读:
    进制
    enum
    文件操作fstream
    文件读取 FILE
    static_cast、dynamic_cast、reinterpret_cast、和const_c
    std::max 错误
    boost 时间
    c++ new 和delete
    c++ static静态
    BOOST 之filesystem, path
  • 原文地址:https://www.cnblogs.com/wangyiming/p/14692058.html
Copyright © 2011-2022 走看看